commit_id,project,commit_message,type,url,git_diff 84ff885f72d1ec8228407b6cdc9c09d342b5a0dc,kotlin,Constructor body generation extracted as a method- (+ migrated to Printer for convenience)--,p,https://github.com/JetBrains/kotlin,"diff --git a/injector-generator/src/org/jetbrains/jet/di/DependencyInjectorGenerator.java b/injector-generator/src/org/jetbrains/jet/di/DependencyInjectorGenerator.java index 6fc139585610e..a0af388cecfbc 100644 --- a/injector-generator/src/org/jetbrains/jet/di/DependencyInjectorGenerator.java +++ b/injector-generator/src/org/jetbrains/jet/di/DependencyInjectorGenerator.java @@ -16,15 +16,13 @@ package org.jetbrains.jet.di; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Lists; -import com.google.common.collect.Multimap; -import com.google.common.collect.Sets; +import com.google.common.collect.*; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.utils.Printer; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @@ -281,70 +279,80 @@ private static DiType getEffectiveFieldType(Field field) { } private void generateConstructor(String injectorClassName, PrintStream out) { - String indent = "" ""; + Printer p = new Printer(out); + p.pushIndent(); // Constructor parameters if (parameters.isEmpty()) { - out.println("" public "" + injectorClassName + ""() {""); + p.println(""public "", injectorClassName, ""() {""); } else { - out.println("" public "" + injectorClassName + ""(""); + p.println(""public "", injectorClassName, ""(""); + p.pushIndent(); for (Iterator iterator = parameters.iterator(); iterator.hasNext(); ) { Parameter parameter = iterator.next(); - out.print(indent); + p.print(); // indent if (parameter.isRequired()) { - out.print(""@NotNull ""); + p.printWithNoIndent(""@NotNull ""); } - out.print(parameter.getType().getSimpleName() + "" "" + parameter.getName()); + p.printWithNoIndent(parameter.getType().getSimpleName(), "" "", parameter.getName()); if (iterator.hasNext()) { - out.println("",""); + p.printlnWithNoIndent("",""); } } - out.println(); - out.println("" ) {""); + p.printlnWithNoIndent(); + p.popIndent(); + p.println("") {""); } + p.pushIndent(); if (lazy) { // Remember parameters for (Parameter parameter : parameters) { - out.println(indent + ""this."" + parameter.getField().getName() + "" = "" + parameter.getName() + "";""); + p.println(""this."", parameter.getField().getName(), "" = "", parameter.getName(), "";""); } } else { - // Initialize fields - for (Field field : fields) { - //if (!backsParameter.contains(field) || field.isPublic()) { - String prefix = ""this.""; - out.println(indent + prefix + field.getName() + "" = "" + field.getInitialization().renderAsCode() + "";""); - //} - } - out.println(); + generateInitializingCode(p, fields); + } - // Call setters - for (Field field : fields) { - for (SetterDependency dependency : field.getDependencies()) { - String prefix = field.isPublic() ? ""this."" : """"; - out.println(indent + prefix + dependency.getDependent().getName() + ""."" + dependency.getSetterName() + ""("" + dependency.getDependency().getName() + "");""); - } - if (!field.getDependencies().isEmpty()) { - out.println(); - } - } + p.popIndent(); + p.println(""}""); + } - // call @PostConstruct - for (Field field : fields) { - // TODO: type of field may be different from type of object - List postConstructMethods = getPostConstructMethods(getEffectiveFieldType(field).getClazz()); - for (Method postConstruct : postConstructMethods) { - out.println(indent + field.getName() + ""."" + postConstruct.getName() + ""();""); - } - if (postConstructMethods.size() > 0) { - out.println(); - } + private static void generateInitializingCode(@NotNull Printer p, @NotNull Collection fields) { + // Initialize fields + for (Field field : fields) { + //if (!backsParameter.contains(field) || field.isPublic()) { + p.println(""this."", field.getName(), "" = "", field.getInitialization().renderAsCode(), "";""); + //} + } + p.printlnWithNoIndent(); + + // Call setters + for (Field field : fields) { + for (SetterDependency dependency : field.getDependencies()) { + String prefix = field.isPublic() ? ""this."" : """"; + String dependencyName = dependency.getDependency().getName(); + String dependentName = dependency.getDependent().getName(); + p.println(prefix, dependentName, ""."", dependency.getSetterName(), ""("", dependencyName, "");""); + } + if (!field.getDependencies().isEmpty()) { + p.printlnWithNoIndent(); } } - out.println("" }""); + // call @PostConstruct + for (Field field : fields) { + // TODO: type of field may be different from type of object + List postConstructMethods = getPostConstructMethods(getEffectiveFieldType(field).getClazz()); + for (Method postConstruct : postConstructMethods) { + p.println(field.getName(), ""."", postConstruct.getName(), ""();""); + } + if (postConstructMethods.size() > 0) { + p.printlnWithNoIndent(); + } + } } private static List getPostConstructMethods(Class clazz) {" e0e1bdf57aa4f1dae1de5b7a51b58fad1fd4696b,brandonborkholder$glg2d,Abstracted some of the init/tear-down functionality to make it easier to customize.,p,https://github.com/brandonborkholder/glg2d,"diff --git a/src/main/java/glg2d/G2DGLCanvas.java b/src/main/java/glg2d/G2DGLCanvas.java index 33a0d734..db9405a2 100644 --- a/src/main/java/glg2d/G2DGLCanvas.java +++ b/src/main/java/glg2d/G2DGLCanvas.java @@ -107,7 +107,7 @@ public boolean isGLDrawing() { /** * Sets the drawing path, {@code true} for OpenGL, {@code false} for normal * Java2D. - * + * * @see #isGLDrawing() */ public void setGLDrawing(boolean drawGL) { @@ -131,12 +131,20 @@ public void setDrawableComponent(JComponent component) { drawableComponent = component; if (drawableComponent != null) { - g2dglListener = new G2DGLEventListener(drawableComponent); + g2dglListener = createG2DListener(drawableComponent); canvas.addGLEventListener(g2dglListener); add(drawableComponent); } } + /** + * Creates the GLEventListener that will draw the given component to the + * canvas. + */ + protected GLEventListener createG2DListener(JComponent drawingComponent) { + return new G2DGLEventListener(drawingComponent); + } + public JComponent getDrawableComponent() { return drawableComponent; } diff --git a/src/main/java/glg2d/G2DGLEventListener.java b/src/main/java/glg2d/G2DGLEventListener.java index bcb48139..c5e0c74f 100644 --- a/src/main/java/glg2d/G2DGLEventListener.java +++ b/src/main/java/glg2d/G2DGLEventListener.java @@ -18,7 +18,9 @@ import java.awt.Component; +import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLContext; import javax.media.opengl.GLEventListener; import javax.swing.RepaintManager; @@ -36,7 +38,7 @@ public class G2DGLEventListener implements GLEventListener { * {@code baseComponent} is used to provide default font, backgroundColor, * etc. to the {@code GLGraphics2D} object. It is also used for width, height * of the viewport in OpenGL. - * + * * @param baseComponent * The component to use for default settings. */ @@ -47,9 +49,73 @@ public G2DGLEventListener(Component baseComponent) { @Override public void display(GLAutoDrawable drawable) { g2d.setCanvas(drawable); - g2d.prePaint(baseComponent); + prePaint(drawable.getContext()); paintGL(g2d); + postPaint(drawable.getContext()); + } + + /** + * Called after the canvas is set on {@code g2d} but before any painting is + * done. This should setup the matrices and ask {@code g2d} to setup any + * client state. + */ + protected void prePaint(GLContext context) { + setupMatrices(context); + g2d.prePaint(baseComponent); + } + + /** + * Sets up the three matrices, including the transform from OpenGL coordinate + * system to Java2D coordinates. + */ + protected void setupMatrices(GLContext context) { + GL gl = context.getGL(); + + // push all the matrices + gl.glMatrixMode(GL.GL_PROJECTION); + gl.glPushMatrix(); + + int width = baseComponent.getWidth(); + int height = baseComponent.getHeight(); + + // and setup the viewport + gl.glViewport(0, 0, width, height); + gl.glLoadIdentity(); + gl.glOrtho(0, width, 0, height, -1, 1); + + gl.glMatrixMode(GL.GL_MODELVIEW); + gl.glPushMatrix(); + gl.glLoadIdentity(); + + // do the transform from Graphics2D coords to openGL coords + gl.glTranslatef(0, height, 0); + gl.glScalef(1, -1, 1); + + gl.glMatrixMode(GL.GL_TEXTURE); + gl.glPushMatrix(); + gl.glLoadIdentity(); + } + + /** + * Called after all Java2D painting is complete. This should restore the + * matrices if they were modified. + */ + protected void postPaint(GLContext context) { g2d.postPaint(); + popMatrices(context); + } + + /** + * Pops all the matrices. + */ + protected void popMatrices(GLContext context) { + GL gl = context.getGL(); + gl.glMatrixMode(GL.GL_MODELVIEW); + gl.glPopMatrix(); + gl.glMatrixMode(GL.GL_PROJECTION); + gl.glPopMatrix(); + gl.glMatrixMode(GL.GL_TEXTURE); + gl.glPopMatrix(); } /** diff --git a/src/main/java/glg2d/GLGraphics2D.java b/src/main/java/glg2d/GLGraphics2D.java index 324c3ed3..f3d4e437 100644 --- a/src/main/java/glg2d/GLGraphics2D.java +++ b/src/main/java/glg2d/GLGraphics2D.java @@ -131,37 +131,9 @@ protected void prePaint(Component component) { gl.glDisable(GL.GL_CULL_FACE); gl.glShadeModel(GL.GL_FLAT); gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); - - // push all the matrices - gl.glMatrixMode(GL.GL_PROJECTION); - gl.glPushMatrix(); - - // and setup the viewport - gl.glViewport(0, 0, width, height); - gl.glLoadIdentity(); - gl.glOrtho(0, width, 0, height, -1, 1); - - gl.glMatrixMode(GL.GL_MODELVIEW); - gl.glPushMatrix(); - gl.glLoadIdentity(); - - // do the transform from Graphics2D coords to openGL coords - gl.glTranslatef(0, height, 0); - gl.glScalef(1, -1, 1); - - gl.glMatrixMode(GL.GL_TEXTURE); - gl.glPushMatrix(); - gl.glLoadIdentity(); } protected void postPaint() { - gl.glMatrixMode(GL.GL_MODELVIEW); - gl.glPopMatrix(); - gl.glMatrixMode(GL.GL_PROJECTION); - gl.glPopMatrix(); - gl.glMatrixMode(GL.GL_TEXTURE); - gl.glPopMatrix(); - gl.glPopClientAttrib(); gl.glPopAttrib(); gl.glFlush();" 4cc637f7b8b94f0cd1a97a6b618e333e7ef4d525,mctcp$terraincontrol,"Refactor CustomObjects and Resources There are now CustomObjects, and all BO2 are a CustomObject. UseWorld and UseBiome are also CustomObjects. Even all trees are now a CustomObject. All resources now inherit Resource. All settings don't have to be stored in a generic Resource object, but they are stored in the resource itself. This allow for more flexibility. Plugin developers can now add their own CustomObjects and Resources. ",p,https://github.com/mctcp/terraincontrol,"diff --git a/bukkit/src/com/khorn/terraincontrol/bukkit/TCListener.java b/bukkit/src/com/khorn/terraincontrol/bukkit/TCListener.java index bbc001aae..9e5d29205 100644 --- a/bukkit/src/com/khorn/terraincontrol/bukkit/TCListener.java +++ b/bukkit/src/com/khorn/terraincontrol/bukkit/TCListener.java @@ -12,20 +12,15 @@ import org.bukkit.event.world.WorldInitEvent; import com.khorn.terraincontrol.configuration.BiomeConfig; -import com.khorn.terraincontrol.configuration.Resource; -import com.khorn.terraincontrol.generator.resourcegens.TreeGen; +import com.khorn.terraincontrol.generator.resourcegens.SaplingGen; public class TCListener implements Listener { private TCPlugin tcPlugin; - private Random random; - - private TreeGen treeGenerator = new TreeGen(); public TCListener(TCPlugin plugin) { this.tcPlugin = plugin; - this.random = new Random(); Bukkit.getServer().getPluginManager().registerEvents(this, plugin); } @@ -51,7 +46,7 @@ public void onStructureGrow(StructureGrowEvent event) return; BiomeConfig biomeConfig = bukkitWorld.getSettings().biomeConfigs[biomeId]; - Resource sapling; + SaplingGen sapling; switch (event.getSpecies()) { @@ -76,8 +71,25 @@ public void onStructureGrow(StructureGrowEvent event) if (sapling != null) { - treeGenerator.SpawnTree(bukkitWorld, this.random, sapling, x, y, z); - event.getBlocks().clear(); + boolean success = false; + for(int i = 0; i < bukkitWorld.getSettings().objectSpawnRatio; i++) + { + if(sapling.growSapling(bukkitWorld, new Random(), x, y, z)) + { + success = true; + break; + } + } + + if(success) + { + // Just spawned the tree, clear the blocks list to prevent Bukkit spawning another tree + event.getBlocks().clear(); + } else + { + // Cannot grow, so leave the sapling there + event.setCancelled(true); + } } } diff --git a/bukkit/src/com/khorn/terraincontrol/bukkit/TCPlugin.java b/bukkit/src/com/khorn/terraincontrol/bukkit/TCPlugin.java index 030e4dfb0..e309e4e64 100644 --- a/bukkit/src/com/khorn/terraincontrol/bukkit/TCPlugin.java +++ b/bukkit/src/com/khorn/terraincontrol/bukkit/TCPlugin.java @@ -6,7 +6,7 @@ import com.khorn.terraincontrol.bukkit.commands.TCCommandExecutor; import com.khorn.terraincontrol.configuration.TCDefaultValues; import com.khorn.terraincontrol.configuration.WorldConfig; -import com.khorn.terraincontrol.customobjects.ObjectsStore; +import com.khorn.terraincontrol.customobjects.BODefaultValues; import com.khorn.terraincontrol.util.Txt; import net.minecraft.server.BiomeBase; import org.bukkit.Bukkit; @@ -50,8 +50,6 @@ public void onEnable() this.listener = new TCListener(this); - ObjectsStore.ReadObjects(this.getDataFolder()); - Bukkit.getMessenger().registerOutgoingPluginChannel(this, TCDefaultValues.ChannelName.stringValue()); TerrainControl.log(""Enabled""); @@ -185,4 +183,10 @@ public LocalWorld getWorld(String name) } return this.worlds.get(world.getUID()); } + + @Override + public File getGlobalObjectsDirectory() + { + return new File(this.getDataFolder(), BODefaultValues.BO_GlobalDirectoryName.stringValue()); + } } \ No newline at end of file diff --git a/bukkit/src/com/khorn/terraincontrol/bukkit/commands/ListCommand.java b/bukkit/src/com/khorn/terraincontrol/bukkit/commands/ListCommand.java index c8efffcff..bce1ac038 100644 --- a/bukkit/src/com/khorn/terraincontrol/bukkit/commands/ListCommand.java +++ b/bukkit/src/com/khorn/terraincontrol/bukkit/commands/ListCommand.java @@ -1,93 +1,91 @@ -package com.khorn.terraincontrol.bukkit.commands; - -import com.khorn.terraincontrol.bukkit.BukkitWorld; -import com.khorn.terraincontrol.bukkit.TCPerm; -import com.khorn.terraincontrol.bukkit.TCPlugin; -import com.khorn.terraincontrol.customobjects.CustomObject; -import com.khorn.terraincontrol.customobjects.CustomObjectCompiled; -import com.khorn.terraincontrol.customobjects.ObjectsStore; -import org.bukkit.command.CommandSender; - -import java.util.ArrayList; -import java.util.List; - -public class ListCommand extends BaseCommand -{ - public ListCommand(TCPlugin _plugin) - { - super(_plugin); - name = ""list""; - perm = TCPerm.CMD_LIST.node; - usage = ""list [-w World] [page]""; - workOnConsole = false; - } - - @Override - public boolean onCommand(CommandSender sender, List args) - { - - int page = 1; - - if (args.size() > 1 && args.get(0).equals(""-w"")) - { - String worldName = args.get(1); - if (args.size() > 2) - { - try - { - page = Integer.parseInt(args.get(2)); - } catch (Exception e) - { - sender.sendMessage(ErrorColor + ""Wrong page number "" + args.get(2)); - } - } - BukkitWorld world = this.getWorld(sender, worldName); - - if (world != null) - { - if (world.getSettings().CustomObjectsCompiled.size() == 0) - sender.sendMessage(MessageColor + ""This world does not have custom objects""); - - List pluginList = new ArrayList(); - for (CustomObjectCompiled object : world.getSettings().CustomObjectsCompiled) - { - pluginList.add(ValueColor + object.Name); - } - - this.ListMessage(sender, pluginList, page, ""World bo2 objects""); - - } else - sender.sendMessage(ErrorColor + ""World not found "" + worldName); - return true; - - - } - if (args.size() > 0) - { - try - { - page = Integer.parseInt(args.get(0)); - } catch (Exception e) - { - sender.sendMessage(ErrorColor + ""Wrong page number "" + args.get(0)); - } - } - - ArrayList globalObjects = ObjectsStore.LoadObjectsFromDirectory(ObjectsStore.GlobalDirectory); - - if (globalObjects.size() == 0) - sender.sendMessage(MessageColor + ""This global directory does not have custom objects""); - - List pluginList = new ArrayList(); - for (CustomObject object : globalObjects) - { - pluginList.add(ValueColor + object.Name); - } - - this.ListMessage(sender, pluginList, page, ""Global bo2 objects""); - - - return true; - - } +package com.khorn.terraincontrol.bukkit.commands; + +import com.khorn.terraincontrol.TerrainControl; +import com.khorn.terraincontrol.bukkit.BukkitWorld; +import com.khorn.terraincontrol.bukkit.TCPerm; +import com.khorn.terraincontrol.bukkit.TCPlugin; +import com.khorn.terraincontrol.customobjects.CustomObject; +import org.bukkit.command.CommandSender; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public class ListCommand extends BaseCommand +{ + public ListCommand(TCPlugin _plugin) + { + super(_plugin); + name = ""list""; + perm = TCPerm.CMD_LIST.node; + usage = ""list [-w World] [page]""; + workOnConsole = false; + } + + @Override + public boolean onCommand(CommandSender sender, List args) + { + + int page = 1; + + if (args.size() > 1 && args.get(0).equals(""-w"")) + { + String worldName = args.get(1); + if (args.size() > 2) + { + try + { + page = Integer.parseInt(args.get(2)); + } catch (Exception e) + { + sender.sendMessage(ErrorColor + ""Wrong page number "" + args.get(2)); + } + } + BukkitWorld world = this.getWorld(sender, worldName); + + if (world != null) + { + if (world.getSettings().customObjects.size() == 0) + sender.sendMessage(MessageColor + ""This world does not have custom objects""); + + List pluginList = new ArrayList(); + for (CustomObject object : world.getSettings().customObjects.values()) + { + pluginList.add(ValueColor + object.getName()); + } + + this.ListMessage(sender, pluginList, page, ""World bo2 objects""); + + } else + sender.sendMessage(ErrorColor + ""World not found "" + worldName); + return true; + + } + if (args.size() > 0) + { + try + { + page = Integer.parseInt(args.get(0)); + } catch (Exception e) + { + sender.sendMessage(ErrorColor + ""Wrong page number "" + args.get(0)); + } + } + + Collection globalObjects = TerrainControl.getCustomObjectManager().globalObjects.values(); + + if (globalObjects.size() == 0) + sender.sendMessage(MessageColor + ""This global directory does not have custom objects""); + + List pluginList = new ArrayList(); + for (CustomObject object : globalObjects) + { + pluginList.add(ValueColor + object.getName()); + } + + this.ListMessage(sender, pluginList, page, ""Global bo2 objects""); + + return true; + + } } \ No newline at end of file diff --git a/bukkit/src/com/khorn/terraincontrol/bukkit/commands/SpawnCommand.java b/bukkit/src/com/khorn/terraincontrol/bukkit/commands/SpawnCommand.java index c706d9558..6c3252e26 100644 --- a/bukkit/src/com/khorn/terraincontrol/bukkit/commands/SpawnCommand.java +++ b/bukkit/src/com/khorn/terraincontrol/bukkit/commands/SpawnCommand.java @@ -1,97 +1,90 @@ -package com.khorn.terraincontrol.bukkit.commands; - -import com.khorn.terraincontrol.bukkit.BukkitWorld; -import com.khorn.terraincontrol.bukkit.TCPerm; -import com.khorn.terraincontrol.bukkit.TCPlugin; -import com.khorn.terraincontrol.customobjects.CustomObjectCompiled; -import com.khorn.terraincontrol.customobjects.CustomObjectGen; -import com.khorn.terraincontrol.customobjects.ObjectsStore; -import org.bukkit.block.Block; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.util.BlockIterator; - -import java.util.Iterator; -import java.util.List; -import java.util.Random; - -public class SpawnCommand extends BaseCommand -{ - public SpawnCommand(TCPlugin _plugin) - { - super(_plugin); - name = ""spawn""; - perm = TCPerm.CMD_SPAWN.node; - usage = ""spawn Name [World]""; - workOnConsole = false; - } - - @Override - public boolean onCommand(CommandSender sender, List args) - { - Player me = (Player) sender; - - BukkitWorld bukkitWorld = this.getWorld(me, args.size() > 1 ? args.get(1) : """"); - - if (args.size() == 0) - { - me.sendMessage(ErrorColor + ""You must enter the name of the BO2.""); - return true; - } - CustomObjectCompiled spawnObject = null; - - if (bukkitWorld != null) - spawnObject = ObjectsStore.CompileString(args.get(0), bukkitWorld.getSettings().CustomObjectsDirectory); - - if (spawnObject == null) - { - me.sendMessage(BaseCommand.MessageColor + ""BO2 not found in world directory. Searching in global directory.""); - spawnObject = ObjectsStore.CompileString(args.get(0), ObjectsStore.GlobalDirectory); - } - - if (spawnObject == null) - { - sender.sendMessage(ErrorColor + ""BO2 not found, use '/tc list' to list the available ones.""); - return true; - } - - Block block = this.getWatchedBlock(me, true); - if (block == null) - return true; - - if (CustomObjectGen.GenerateCustomObject(bukkitWorld, new Random(), block.getX(), block.getY(), block.getZ(), spawnObject)) - { - me.sendMessage(BaseCommand.MessageColor + spawnObject.Name + "" was spawned.""); - } else - { - me.sendMessage(BaseCommand.ErrorColor + ""BO2 cant be spawned over there.""); - } - - return true; - } - - public Block getWatchedBlock(Player me, boolean verbose) - { - if (me == null) - return null; - - Block block; - - Iterator itr = new BlockIterator(me, 200); - while (itr.hasNext()) - { - block = itr.next(); - if (block.getTypeId() != 0) - { - return block; - } - } - - if (verbose) - { - me.sendMessage(ErrorColor + ""No block in sight.""); - } - - return null; - } +package com.khorn.terraincontrol.bukkit.commands; + +import com.khorn.terraincontrol.TerrainControl; +import com.khorn.terraincontrol.bukkit.BukkitWorld; +import com.khorn.terraincontrol.bukkit.TCPerm; +import com.khorn.terraincontrol.bukkit.TCPlugin; +import com.khorn.terraincontrol.customobjects.CustomObject; +import org.bukkit.block.Block; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.BlockIterator; + +import java.util.Iterator; +import java.util.List; +import java.util.Random; + +public class SpawnCommand extends BaseCommand +{ + public SpawnCommand(TCPlugin _plugin) + { + super(_plugin); + name = ""spawn""; + perm = TCPerm.CMD_SPAWN.node; + usage = ""spawn Name [World]""; + workOnConsole = false; + } + + @Override + public boolean onCommand(CommandSender sender, List args) + { + Player me = (Player) sender; + + BukkitWorld bukkitWorld = this.getWorld(me, args.size() > 1 ? args.get(1) : """"); + + if (args.size() == 0) + { + me.sendMessage(ErrorColor + ""You must enter the name of the BO2.""); + return true; + } + CustomObject spawnObject = null; + + if (bukkitWorld != null) + spawnObject = TerrainControl.getCustomObjectManager().getObjectFromString(args.get(0), bukkitWorld); + + if (spawnObject == null) + { + sender.sendMessage(ErrorColor + ""Object not found, use '/tc list' to list the available ones.""); + return true; + } + + Block block = this.getWatchedBlock(me, true); + if (block == null) + return true; + + if (spawnObject.spawn(bukkitWorld, new Random(), block.getX(), block.getY(), block.getZ())) + { + me.sendMessage(BaseCommand.MessageColor + spawnObject.getName() + "" was spawned.""); + } else + { + me.sendMessage(BaseCommand.ErrorColor + ""BO2 cant be spawned over there.""); + } + + return true; + } + + public Block getWatchedBlock(Player me, boolean verbose) + { + if (me == null) + return null; + + Block block; + + Iterator itr = new BlockIterator(me, 200); + while (itr.hasNext()) + { + block = itr.next(); + if (block.getTypeId() != 0) + { + return block; + } + } + + if (verbose) + { + me.sendMessage(ErrorColor + ""No block in sight.""); + } + + return null; + } } \ No newline at end of file diff --git a/common/src/com/khorn/terraincontrol/TerrainControl.java b/common/src/com/khorn/terraincontrol/TerrainControl.java index 0384414d4..5fa04436f 100644 --- a/common/src/com/khorn/terraincontrol/TerrainControl.java +++ b/common/src/com/khorn/terraincontrol/TerrainControl.java @@ -1,10 +1,37 @@ package com.khorn.terraincontrol; +import java.util.HashMap; +import java.util.Map; import java.util.logging.Level; +import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.customobjects.CustomObject; +import com.khorn.terraincontrol.customobjects.CustomObjectLoader; +import com.khorn.terraincontrol.customobjects.CustomObjectManager; +import com.khorn.terraincontrol.generator.resourcegens.ResourcesManager; + public class TerrainControl { + /** + * The world height that the engine supports. Not the actual height the + * world is capped at. 256 in Minecraft. + */ + public static int worldHeight = 256; + + /** + * The world depth that the engine supports. Not the actual depth the world + * is capped at. 0 in Minecraft. + */ + public static int worldDepth = 0; + private static TerrainControlEngine engine; + private static ResourcesManager resourcesManager; + private static CustomObjectManager customObjectManager; + + // Used before TerrainControl is initialized + private static Map customObjectLoaders = new HashMap(); + private static Map specialCustomObjects; + private static Map> resourceTypes; private TerrainControl() { @@ -12,7 +39,7 @@ private TerrainControl() } /** - * Starts the engine, making all API methods availible. + * Starts the engine, making all API methods available. * * @param engine * The implementation of the engine. @@ -24,6 +51,24 @@ public static void startEngine(TerrainControlEngine engine) throw new UnsupportedOperationException(""Engine is already set!""); } TerrainControl.engine = engine; + + if (customObjectLoaders == null) + { + customObjectLoaders = new HashMap(); + } + if (specialCustomObjects == null) + { + specialCustomObjects = new HashMap(); + } + customObjectManager = new CustomObjectManager(customObjectLoaders, specialCustomObjects); + + if (resourceTypes == null) + { + resourceTypes = new HashMap>(); + } + + resourcesManager = new ResourcesManager(resourceTypes); + //resourcesManager.start(resourceTypes); } /** @@ -33,6 +78,12 @@ public static void startEngine(TerrainControlEngine engine) public static void stopEngine() { engine = null; + customObjectManager = null; + resourcesManager = null; + + customObjectLoaders.clear(); + specialCustomObjects.clear(); + resourceTypes.clear(); } /** @@ -105,4 +156,75 @@ public static void log(Level level, String... messages) { engine.log(level, messages); } + + /** + * Returns the CustomObject manager, with hooks to spawn CustomObjects. + * + * @return The CustomObject manager. + */ + public static CustomObjectManager getCustomObjectManager() + { + return customObjectManager; + } + + /** + * Returns the Resource manager. + * + * @return The Resource manager. + */ + public static ResourcesManager getResourcesManager() + { + return resourcesManager; + } + + /** + * Registers a CustomObject loader. Can be called before Terrain Control is + * fully loaded. + * + * @param extension + * The file extension, without a dot. + * @param loader + * The loader. + */ + public static void registerCustomObjectLoader(String extension, CustomObjectLoader loader) + { + if (customObjectLoaders == null) + { + customObjectLoaders = new HashMap(); + } + customObjectLoaders.put(extension.toLowerCase(), loader); + } + + /** + * Registers a special CustomObject, like UseWorld or UseBiome or a tree. + * Can be called before Terrain Control is fully loaded. + * + * @param extension + * @param loader + */ + public static void registerSpecialCustomObject(String name, CustomObject object) + { + if (specialCustomObjects == null) + { + specialCustomObjects = new HashMap(); + } + specialCustomObjects.put(name.toLowerCase(), object); + } + + /** + * Register a new Resource type. Can be called before Terrain Control is + * fully loaded. + * + * @param name + * @param resourceType + */ + public static void registerResourceType(String name, Class resourceType) + { + if (resourceTypes == null) + { + resourceTypes = new HashMap>(); + } + resourceTypes.put(name.toLowerCase(), resourceType); + } + } diff --git a/common/src/com/khorn/terraincontrol/TerrainControlEngine.java b/common/src/com/khorn/terraincontrol/TerrainControlEngine.java index 118bda6a0..c3f5c54ed 100644 --- a/common/src/com/khorn/terraincontrol/TerrainControlEngine.java +++ b/common/src/com/khorn/terraincontrol/TerrainControlEngine.java @@ -1,5 +1,6 @@ package com.khorn.terraincontrol; +import java.io.File; import java.util.logging.Level; public interface TerrainControlEngine @@ -9,11 +10,17 @@ public interface TerrainControlEngine * @param name The name of the world. * @return The world object. */ - public abstract LocalWorld getWorld(String name); + public LocalWorld getWorld(String name); /** * Logs the messages. * @param message The messages to log. */ - public abstract void log(Level level, String... message); + public void log(Level level, String... message); + + /** + * Returns the folder where the global objects are stored in. + * @return + */ + public File getGlobalObjectsDirectory(); } diff --git a/common/src/com/khorn/terraincontrol/configuration/BiomeConfig.java b/common/src/com/khorn/terraincontrol/configuration/BiomeConfig.java index b72c0087e..0d4d81fb3 100644 --- a/common/src/com/khorn/terraincontrol/configuration/BiomeConfig.java +++ b/common/src/com/khorn/terraincontrol/configuration/BiomeConfig.java @@ -4,11 +4,26 @@ import com.khorn.terraincontrol.DefaultMaterial; import com.khorn.terraincontrol.DefaultMobType; import com.khorn.terraincontrol.LocalBiome; -import com.khorn.terraincontrol.customobjects.BODefaultValues; -import com.khorn.terraincontrol.customobjects.CustomObjectCompiled; -import com.khorn.terraincontrol.customobjects.ObjectsStore; +import com.khorn.terraincontrol.LocalWorld; +import com.khorn.terraincontrol.TerrainControl; +import com.khorn.terraincontrol.customobjects.CustomObject; +import com.khorn.terraincontrol.generator.resourcegens.AboveWaterGen; +import com.khorn.terraincontrol.generator.resourcegens.CactusGen; +import com.khorn.terraincontrol.generator.resourcegens.CustomObjectGen; +import com.khorn.terraincontrol.generator.resourcegens.DungeonGen; +import com.khorn.terraincontrol.generator.resourcegens.GrassGen; +import com.khorn.terraincontrol.generator.resourcegens.LiquidGen; +import com.khorn.terraincontrol.generator.resourcegens.OreGen; +import com.khorn.terraincontrol.generator.resourcegens.PlantGen; +import com.khorn.terraincontrol.generator.resourcegens.ReedGen; import com.khorn.terraincontrol.generator.resourcegens.ResourceType; +import com.khorn.terraincontrol.generator.resourcegens.SaplingGen; +import com.khorn.terraincontrol.generator.resourcegens.SmallLakeGen; +import com.khorn.terraincontrol.generator.resourcegens.TreeGen; import com.khorn.terraincontrol.generator.resourcegens.TreeType; +import com.khorn.terraincontrol.generator.resourcegens.UnderWaterOreGen; +import com.khorn.terraincontrol.generator.resourcegens.UndergroundLakeGen; +import com.khorn.terraincontrol.generator.resourcegens.VinesGen; import com.khorn.terraincontrol.util.Txt; import java.io.DataInputStream; @@ -16,6 +31,7 @@ import java.io.File; import java.io.IOException; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; @@ -33,7 +49,7 @@ public class BiomeConfig extends ConfigFile public ArrayList IsleInBiome; public ArrayList NotBorderNear; - //Surface config + // Surface config public float BiomeHeight; public float BiomeVolatility; @@ -47,7 +63,6 @@ public class BiomeConfig extends ConfigFile public String ReplaceBiomeName; - public boolean UseWorldWaterLevel; public int waterLevelMax; public int waterLevelMin; @@ -63,10 +78,11 @@ public class BiomeConfig extends ConfigFile public boolean FoliageColorIsMultiplier; public Resource[] ResourceSequence = new Resource[256]; - public Resource[] SaplingTypes = new Resource[4]; - public Resource SaplingResource = null; + public SaplingGen[] SaplingTypes = new SaplingGen[4]; + public SaplingGen SaplingResource = null; - public ArrayList CustomObjectsCompiled; + public ArrayList biomeObjects; + public ArrayList biomeObjectStrings; public double maxAverageHeight; public double maxAverageDepth; @@ -83,13 +99,12 @@ public class BiomeConfig extends ConfigFile public int ResourceCount = 0; - public LocalBiome Biome; public WorldConfig worldConfig; public String Name; - //Spawn Config + // Spawn Config public boolean spawnMonstersAddDefaults = true; public List spawnMonsters = new ArrayList(); public boolean spawnCreaturesAddDefaults = true; @@ -124,12 +139,10 @@ public BiomeConfig(File settingsDir, LocalBiome biome, WorldConfig config) this.iceBlock = worldConfig.iceBlock; } - if (biome.isCustom()) biome.setVisuals(this); } - public int getTemperature() { return (int) (this.BiomeTemperature * 65536.0F); @@ -144,199 +157,193 @@ private void CreateDefaultResources() { Resource resource; - //Small lakes - resource = new Resource(ResourceType.SmallLake, DefaultMaterial.WATER.id, TCDefaultValues.SmallLakeWaterFrequency.intValue(), TCDefaultValues.SmallLakeWaterRarity.intValue(), TCDefaultValues.SmallLakeMinAltitude.intValue(), TCDefaultValues.SmallLakeMaxAltitude.intValue()); + // Small lakes + resource = Resource.create(worldConfig, SmallLakeGen.class, DefaultMaterial.WATER.id, TCDefaultValues.SmallLakeWaterFrequency.intValue(), TCDefaultValues.SmallLakeWaterRarity.intValue(), TCDefaultValues.SmallLakeMinAltitude.intValue(), TCDefaultValues.SmallLakeMaxAltitude.intValue()); this.ResourceSequence[this.ResourceCount++] = resource; - //Small lakes - resource = new Resource(ResourceType.SmallLake, DefaultMaterial.LAVA.id, TCDefaultValues.SmallLakeLavaFrequency.intValue(), TCDefaultValues.SmallLakeLavaRarity.intValue(), TCDefaultValues.SmallLakeMinAltitude.intValue(), TCDefaultValues.SmallLakeMaxAltitude.intValue()); + // Small lakes + resource = Resource.create(worldConfig, SmallLakeGen.class, DefaultMaterial.LAVA.id, TCDefaultValues.SmallLakeLavaFrequency.intValue(), TCDefaultValues.SmallLakeLavaRarity.intValue(), TCDefaultValues.SmallLakeMinAltitude.intValue(), TCDefaultValues.SmallLakeMaxAltitude.intValue()); this.ResourceSequence[this.ResourceCount++] = resource; - //Underground lakes - resource = new Resource(ResourceType.UnderGroundLake, TCDefaultValues.undergroundLakeMinSize.intValue(), TCDefaultValues.undergroundLakeMaxSize.intValue(), TCDefaultValues.undergroundLakeFrequency.intValue(), TCDefaultValues.undergroundLakeRarity.intValue(), TCDefaultValues.undergroundLakeMinAltitude.intValue(), TCDefaultValues.undergroundLakeMaxAltitude.intValue()); + // Underground lakes + resource = Resource.create(worldConfig, UndergroundLakeGen.class, TCDefaultValues.undergroundLakeMinSize.intValue(), TCDefaultValues.undergroundLakeMaxSize.intValue(), TCDefaultValues.undergroundLakeFrequency.intValue(), TCDefaultValues.undergroundLakeRarity.intValue(), TCDefaultValues.undergroundLakeMinAltitude.intValue(), TCDefaultValues.undergroundLakeMaxAltitude.intValue()); this.ResourceSequence[this.ResourceCount++] = resource; - //Dungeon - resource = new Resource(ResourceType.Dungeon, 0, 0, 0, TCDefaultValues.dungeonFrequency.intValue(), TCDefaultValues.dungeonRarity.intValue(), TCDefaultValues.dungeonMinAltitude.intValue(), this.worldConfig.WorldHeight, new int[]{DefaultMaterial.STONE.id}); + // Dungeon + resource = Resource.create(worldConfig, DungeonGen.class, TCDefaultValues.dungeonFrequency.intValue(), TCDefaultValues.dungeonRarity.intValue(), TCDefaultValues.dungeonMinAltitude.intValue(), this.worldConfig.WorldHeight); this.ResourceSequence[this.ResourceCount++] = resource; - //Resource(ResourceType type,int blockId, int blockData, int size,int frequency, int rarity, int minAltitude,int maxAltitude,int[] sourceBlockIds) - //Dirt - resource = new Resource(ResourceType.Ore, DefaultMaterial.DIRT.id, 0, TCDefaultValues.dirtDepositSize.intValue(), TCDefaultValues.dirtDepositFrequency.intValue(), TCDefaultValues.dirtDepositRarity.intValue(), TCDefaultValues.dirtDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, new int[]{DefaultMaterial.STONE.id}); + // Dirt + resource = Resource.create(worldConfig, OreGen.class, DefaultMaterial.DIRT.id, TCDefaultValues.dirtDepositSize.intValue(), TCDefaultValues.dirtDepositFrequency.intValue(), TCDefaultValues.dirtDepositRarity.intValue(), TCDefaultValues.dirtDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, DefaultMaterial.STONE.id); this.ResourceSequence[this.ResourceCount++] = resource; - //Gravel - resource = new Resource(ResourceType.Ore, DefaultMaterial.GRAVEL.id, 0, TCDefaultValues.gravelDepositSize.intValue(), TCDefaultValues.gravelDepositFrequency.intValue(), TCDefaultValues.gravelDepositRarity.intValue(), TCDefaultValues.gravelDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, new int[]{DefaultMaterial.STONE.id}); + // Gravel + resource = Resource.create(worldConfig, OreGen.class, DefaultMaterial.GRAVEL.id, TCDefaultValues.gravelDepositSize.intValue(), TCDefaultValues.gravelDepositFrequency.intValue(), TCDefaultValues.gravelDepositRarity.intValue(), TCDefaultValues.gravelDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, DefaultMaterial.STONE.id); this.ResourceSequence[this.ResourceCount++] = resource; - //Clay - resource = new Resource(ResourceType.Ore, DefaultMaterial.CLAY.id, 0, TCDefaultValues.clayDepositSize.intValue(), TCDefaultValues.clayDepositFrequency.intValue(), TCDefaultValues.clayDepositRarity.intValue(), TCDefaultValues.clayDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, new int[]{DefaultMaterial.STONE.id}); + // Clay + resource = Resource.create(worldConfig, OreGen.class, DefaultMaterial.CLAY.id, TCDefaultValues.clayDepositSize.intValue(), TCDefaultValues.clayDepositFrequency.intValue(), TCDefaultValues.clayDepositRarity.intValue(), TCDefaultValues.clayDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, DefaultMaterial.STONE.id); this.ResourceSequence[this.ResourceCount++] = resource; - //Coal - resource = new Resource(ResourceType.Ore, DefaultMaterial.COAL_ORE.id, 0, TCDefaultValues.coalDepositSize.intValue(), TCDefaultValues.coalDepositFrequency.intValue(), TCDefaultValues.coalDepositRarity.intValue(), TCDefaultValues.coalDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, new int[]{DefaultMaterial.STONE.id}); + // Coal + resource = Resource.create(worldConfig, OreGen.class, DefaultMaterial.COAL_ORE.id, TCDefaultValues.coalDepositSize.intValue(), TCDefaultValues.coalDepositFrequency.intValue(), TCDefaultValues.coalDepositRarity.intValue(), TCDefaultValues.coalDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, DefaultMaterial.STONE.id); this.ResourceSequence[this.ResourceCount++] = resource; - //Iron - resource = new Resource(ResourceType.Ore, DefaultMaterial.IRON_ORE.id, 0, TCDefaultValues.ironDepositSize.intValue(), TCDefaultValues.ironDepositFrequency.intValue(), TCDefaultValues.ironDepositRarity.intValue(), TCDefaultValues.ironDepositMinAltitude.intValue(), this.worldConfig.WorldHeight / 2, new int[]{DefaultMaterial.STONE.id}); + // Iron + resource = Resource.create(worldConfig, OreGen.class, DefaultMaterial.IRON_ORE.id, TCDefaultValues.ironDepositSize.intValue(), TCDefaultValues.ironDepositFrequency.intValue(), TCDefaultValues.ironDepositRarity.intValue(), TCDefaultValues.ironDepositMinAltitude.intValue(), this.worldConfig.WorldHeight / 2, DefaultMaterial.STONE.id); this.ResourceSequence[this.ResourceCount++] = resource; - //Gold - resource = new Resource(ResourceType.Ore, DefaultMaterial.GOLD_ORE.id, 0, TCDefaultValues.goldDepositSize.intValue(), TCDefaultValues.goldDepositFrequency.intValue(), TCDefaultValues.goldDepositRarity.intValue(), TCDefaultValues.goldDepositMinAltitude.intValue(), this.worldConfig.WorldHeight / 4, new int[]{DefaultMaterial.STONE.id}); + // Gold + resource = Resource.create(worldConfig, OreGen.class, DefaultMaterial.GOLD_ORE.id, TCDefaultValues.goldDepositSize.intValue(), TCDefaultValues.goldDepositFrequency.intValue(), TCDefaultValues.goldDepositRarity.intValue(), TCDefaultValues.goldDepositMinAltitude.intValue(), this.worldConfig.WorldHeight / 4, DefaultMaterial.STONE.id); this.ResourceSequence[this.ResourceCount++] = resource; - //Redstone - resource = new Resource(ResourceType.Ore, DefaultMaterial.REDSTONE_ORE.id, 0, TCDefaultValues.redstoneDepositSize.intValue(), TCDefaultValues.redstoneDepositFrequency.intValue(), TCDefaultValues.redstoneDepositRarity.intValue(), TCDefaultValues.redstoneDepositMinAltitude.intValue(), this.worldConfig.WorldHeight / 8, new int[]{DefaultMaterial.STONE.id}); + // Redstone + resource = Resource.create(worldConfig, OreGen.class, DefaultMaterial.REDSTONE_ORE.id, TCDefaultValues.redstoneDepositSize.intValue(), TCDefaultValues.redstoneDepositFrequency.intValue(), TCDefaultValues.redstoneDepositRarity.intValue(), TCDefaultValues.redstoneDepositMinAltitude.intValue(), this.worldConfig.WorldHeight / 8, DefaultMaterial.STONE.id); this.ResourceSequence[this.ResourceCount++] = resource; - //Diamond - resource = new Resource(ResourceType.Ore, DefaultMaterial.DIAMOND_ORE.id, 0, TCDefaultValues.diamondDepositSize.intValue(), TCDefaultValues.diamondDepositFrequency.intValue(), TCDefaultValues.diamondDepositRarity.intValue(), TCDefaultValues.diamondDepositMinAltitude.intValue(), this.worldConfig.WorldHeight / 8, new int[]{DefaultMaterial.STONE.id}); + // Diamond + resource = Resource.create(worldConfig, OreGen.class, DefaultMaterial.DIAMOND_ORE.id, TCDefaultValues.diamondDepositSize.intValue(), TCDefaultValues.diamondDepositFrequency.intValue(), TCDefaultValues.diamondDepositRarity.intValue(), TCDefaultValues.diamondDepositMinAltitude.intValue(), this.worldConfig.WorldHeight / 8, DefaultMaterial.STONE.id); this.ResourceSequence[this.ResourceCount++] = resource; - //Lapislazuli - resource = new Resource(ResourceType.Ore, DefaultMaterial.LAPIS_ORE.id, 0, TCDefaultValues.lapislazuliDepositSize.intValue(), TCDefaultValues.lapislazuliDepositFrequency.intValue(), TCDefaultValues.lapislazuliDepositRarity.intValue(), TCDefaultValues.lapislazuliDepositMinAltitude.intValue(), this.worldConfig.WorldHeight / 8, new int[]{DefaultMaterial.STONE.id}); + // Lapislazuli + resource = Resource.create(worldConfig, OreGen.class, DefaultMaterial.LAPIS_ORE.id, TCDefaultValues.lapislazuliDepositSize.intValue(), TCDefaultValues.lapislazuliDepositFrequency.intValue(), TCDefaultValues.lapislazuliDepositRarity.intValue(), TCDefaultValues.lapislazuliDepositMinAltitude.intValue(), this.worldConfig.WorldHeight / 8, DefaultMaterial.STONE.id); this.ResourceSequence[this.ResourceCount++] = resource; DefaultBiome biome = DefaultBiome.getBiome(this.Biome.getId()); if (biome != null && (biome == DefaultBiome.EXTREME_HILLS || biome == DefaultBiome.SMALL_MOUNTAINS)) { - resource = new Resource(ResourceType.Ore, DefaultMaterial.EMERALD_ORE.id, 0, TCDefaultValues.emeraldDepositSize.intValue(), TCDefaultValues.emeraldDepositFrequency.intValue(), TCDefaultValues.emeraldDepositRarity.intValue(), TCDefaultValues.emeraldDepositMinAltitude.intValue(), this.worldConfig.WorldHeight / 4, new int[]{DefaultMaterial.STONE.id}); + resource = Resource.create(worldConfig, OreGen.class, DefaultMaterial.EMERALD_ORE.id, TCDefaultValues.emeraldDepositSize.intValue(), TCDefaultValues.emeraldDepositFrequency.intValue(), TCDefaultValues.emeraldDepositRarity.intValue(), TCDefaultValues.emeraldDepositMinAltitude.intValue(), this.worldConfig.WorldHeight / 4, DefaultMaterial.STONE.id); this.ResourceSequence[this.ResourceCount++] = resource; } - //Under water sand - resource = new Resource(ResourceType.UnderWaterOre, DefaultMaterial.SAND.id, 0, TCDefaultValues.waterSandDepositSize.intValue(), TCDefaultValues.waterSandDepositFrequency.intValue(), TCDefaultValues.waterSandDepositRarity.intValue(), 0, 0, new int[]{DefaultMaterial.DIRT.id, DefaultMaterial.GRASS.id}); + // Under water sand + resource = Resource.create(worldConfig, UnderWaterOreGen.class, DefaultMaterial.SAND.id, TCDefaultValues.waterSandDepositSize.intValue(), TCDefaultValues.waterSandDepositFrequency.intValue(), TCDefaultValues.waterSandDepositRarity.intValue(), DefaultMaterial.DIRT.id, DefaultMaterial.GRASS.id); this.ResourceSequence[this.ResourceCount++] = resource; - //Under water clay + // Under water clay if (this.DefaultClay > 0) { - resource = new Resource(ResourceType.UnderWaterOre, DefaultMaterial.CLAY.id, 0, TCDefaultValues.waterClayDepositSize.intValue(), this.DefaultClay, TCDefaultValues.waterClayDepositRarity.intValue(), 0, 0, new int[]{DefaultMaterial.DIRT.id, DefaultMaterial.CLAY.id}); + resource = Resource.create(worldConfig, UnderWaterOreGen.class, DefaultMaterial.CLAY.id, TCDefaultValues.waterClayDepositSize.intValue(), this.DefaultClay, TCDefaultValues.waterClayDepositRarity.intValue(), DefaultMaterial.DIRT.id, DefaultMaterial.CLAY.id); this.ResourceSequence[this.ResourceCount++] = resource; } - //Custom objects - resource = new Resource(ResourceType.CustomObject); - ResourceType.CustomObject.Generator.ReadFromString(resource, new String[]{BODefaultValues.BO_Use_World.stringValue()}, this); + // Custom objects + resource = Resource.create(worldConfig, CustomObjectGen.class, ""UseWorld""); this.ResourceSequence[this.ResourceCount++] = resource; - + // Trees if (biome != null) switch (biome) { - case OCEAN: // Ocean - default - case EXTREME_HILLS: // BigHills - default - case RIVER: // River - default - case SMALL_MOUNTAINS: // SmallHills - resource = new Resource(ResourceType.Tree, this.DefaultTrees, new TreeType[]{TreeType.BigTree, TreeType.Tree}, new int[]{1, 9}); - this.ResourceSequence[this.ResourceCount++] = resource; - break; - case PLAINS: // Plains - no tree - case DESERT: // Desert - no tree - case DESERT_HILLS: //HillsDesert - break; - case FOREST_HILLS: // HillsForest - case FOREST: // Forest - forest - resource = new Resource(ResourceType.Tree, this.DefaultTrees, new TreeType[]{TreeType.Forest, TreeType.BigTree, TreeType.Tree}, new int[]{20, 10, 100}); - this.ResourceSequence[this.ResourceCount++] = resource; - break; - case TAIGA_HILLS: //HillsTaiga - case TAIGA: // Taiga - taiga - resource = new Resource(ResourceType.Tree, this.DefaultTrees, new TreeType[]{TreeType.Taiga1, TreeType.Taiga2}, new int[]{35, 100}); - this.ResourceSequence[this.ResourceCount++] = resource; - break; - case SWAMPLAND: // Swamp - swamp - resource = new Resource(ResourceType.Tree, this.DefaultTrees, new TreeType[]{TreeType.SwampTree}, new int[]{100}); - this.ResourceSequence[this.ResourceCount++] = resource; - break; - case MUSHROOM_ISLAND: // Mushroom island - resource = new Resource(ResourceType.Tree, this.DefaultTrees, new TreeType[]{TreeType.HugeMushroom}, new int[]{100}); - this.ResourceSequence[this.ResourceCount++] = resource; - break; - case JUNGLE:// Jungle - case JUNGLE_HILLS: - resource = new Resource(ResourceType.Tree, this.DefaultTrees, new TreeType[]{TreeType.BigTree, TreeType.GroundBush, TreeType.JungleTree, TreeType.CocoaTree}, new int[]{10, 50, 35, 100}); - this.ResourceSequence[this.ResourceCount++] = resource; - break; - + case OCEAN: // Ocean - default + case EXTREME_HILLS: // BigHills - default + case RIVER: // River - default + case SMALL_MOUNTAINS: // SmallHills + resource = Resource.create(worldConfig, TreeGen.class, this.DefaultTrees, TreeType.BigTree, 1, TreeType.Tree, 9); + this.ResourceSequence[this.ResourceCount++] = resource; + break; + case PLAINS: // Plains - no tree + case DESERT: // Desert - no tree + case DESERT_HILLS: // HillsDesert + break; + case FOREST_HILLS: // HillsForest + case FOREST: // Forest - forest + resource = Resource.create(worldConfig, TreeGen.class, this.DefaultTrees, TreeType.Forest, 20, TreeType.BigTree, 10, TreeType.Tree, 100); + this.ResourceSequence[this.ResourceCount++] = resource; + break; + case TAIGA_HILLS: // HillsTaiga + case TAIGA: // Taiga - taiga + resource = Resource.create(worldConfig, TreeGen.class, this.DefaultTrees, TreeType.Taiga1, 35, TreeType.Taiga2, 100); + this.ResourceSequence[this.ResourceCount++] = resource; + break; + case SWAMPLAND: // Swamp - swamp + resource = Resource.create(worldConfig, TreeGen.class, this.DefaultTrees, TreeType.SwampTree, 100); + this.ResourceSequence[this.ResourceCount++] = resource; + break; + case MUSHROOM_ISLAND: // Mushroom island + resource = Resource.create(worldConfig, TreeGen.class, this.DefaultTrees, TreeType.HugeMushroom, 100); + this.ResourceSequence[this.ResourceCount++] = resource; + break; + case JUNGLE:// Jungle + case JUNGLE_HILLS: + resource = Resource.create(worldConfig, TreeGen.class, this.DefaultTrees, TreeType.BigTree, 10, TreeType.GroundBush, 50, TreeType.JungleTree, 35, TreeType.CocoaTree, 100); + this.ResourceSequence[this.ResourceCount++] = resource; + break; } if (this.DefaultWaterLily > 0) { - resource = new Resource(ResourceType.AboveWaterRes, DefaultMaterial.WATER_LILY.id, 0, 0, this.DefaultWaterLily, 100, 0, 0, new int[0]); + resource = Resource.create(worldConfig, AboveWaterGen.class, DefaultMaterial.WATER_LILY.id, this.DefaultWaterLily, 100); this.ResourceSequence[this.ResourceCount++] = resource; } if (this.DefaultFlowers > 0) { - //Red flower - resource = new Resource(ResourceType.Plant, DefaultMaterial.RED_ROSE.id, 0, 0, this.DefaultFlowers, TCDefaultValues.roseDepositRarity.intValue(), TCDefaultValues.roseDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, new int[]{DefaultMaterial.GRASS.id, DefaultMaterial.DIRT.id, DefaultMaterial.SOIL.id}); + // Red flower + resource = Resource.create(worldConfig, PlantGen.class, DefaultMaterial.RED_ROSE.id, this.DefaultFlowers, TCDefaultValues.roseDepositRarity.intValue(), TCDefaultValues.roseDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, DefaultMaterial.GRASS.id, DefaultMaterial.DIRT.id, DefaultMaterial.SOIL.id); this.ResourceSequence[this.ResourceCount++] = resource; - //Yellow flower - resource = new Resource(ResourceType.Plant, DefaultMaterial.YELLOW_FLOWER.id, 0, 0, this.DefaultFlowers, TCDefaultValues.flowerDepositRarity.intValue(), TCDefaultValues.flowerDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, new int[]{DefaultMaterial.GRASS.id, DefaultMaterial.DIRT.id, DefaultMaterial.SOIL.id}); + // Yellow flower + resource = Resource.create(worldConfig, PlantGen.class, DefaultMaterial.YELLOW_FLOWER.id, this.DefaultFlowers, TCDefaultValues.flowerDepositRarity.intValue(), TCDefaultValues.flowerDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, DefaultMaterial.GRASS.id, DefaultMaterial.DIRT.id, DefaultMaterial.SOIL.id); this.ResourceSequence[this.ResourceCount++] = resource; } if (this.DefaultMushroom > 0) { - //Red mushroom - resource = new Resource(ResourceType.Plant, DefaultMaterial.RED_MUSHROOM.id, 0, 0, this.DefaultMushroom, TCDefaultValues.redMushroomDepositRarity.intValue(), TCDefaultValues.redMushroomDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, new int[]{DefaultMaterial.GRASS.id, DefaultMaterial.DIRT.id}); + // Red mushroom + resource = Resource.create(worldConfig, PlantGen.class, DefaultMaterial.RED_MUSHROOM.id, this.DefaultMushroom, TCDefaultValues.redMushroomDepositRarity.intValue(), TCDefaultValues.redMushroomDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, DefaultMaterial.GRASS.id, DefaultMaterial.DIRT.id); this.ResourceSequence[this.ResourceCount++] = resource; - //Brown mushroom - resource = new Resource(ResourceType.Plant, DefaultMaterial.BROWN_MUSHROOM.id, 0, 0, this.DefaultMushroom, TCDefaultValues.brownMushroomDepositRarity.intValue(), TCDefaultValues.brownMushroomDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, new int[]{DefaultMaterial.GRASS.id, DefaultMaterial.DIRT.id}); + // Brown mushroom + resource = Resource.create(worldConfig, PlantGen.class, DefaultMaterial.BROWN_MUSHROOM.id, this.DefaultMushroom, TCDefaultValues.brownMushroomDepositRarity.intValue(), TCDefaultValues.brownMushroomDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, DefaultMaterial.GRASS.id, DefaultMaterial.DIRT.id); this.ResourceSequence[this.ResourceCount++] = resource; } if (this.DefaultGrass > 0) { - //Grass - resource = new Resource(ResourceType.Grass, DefaultMaterial.LONG_GRASS.id, 1, 0, this.DefaultGrass, TCDefaultValues.longGrassDepositRarity.intValue(), 0, 0, new int[]{DefaultMaterial.GRASS.id, DefaultMaterial.DIRT.id}); + // Grass + resource = Resource.create(worldConfig, GrassGen.class, DefaultMaterial.LONG_GRASS.id, 1, this.DefaultGrass, TCDefaultValues.longGrassDepositRarity.intValue(), DefaultMaterial.GRASS.id, DefaultMaterial.DIRT.id); this.ResourceSequence[this.ResourceCount++] = resource; } if (this.DefaultDeadBrush > 0) { - //Dead Bush - resource = new Resource(ResourceType.Grass, DefaultMaterial.DEAD_BUSH.id, 0, 0, this.DefaultDeadBrush, TCDefaultValues.deadBushDepositRarity.intValue(), 0, 0, new int[]{DefaultMaterial.SAND.id}); + // Dead Bush + resource = Resource.create(worldConfig, GrassGen.class, DefaultMaterial.DEAD_BUSH.id, 0, this.DefaultDeadBrush, TCDefaultValues.deadBushDepositRarity.intValue(), DefaultMaterial.SAND.id); this.ResourceSequence[this.ResourceCount++] = resource; } - //Pumpkin - resource = new Resource(ResourceType.Plant, DefaultMaterial.PUMPKIN.id, 0, 0, TCDefaultValues.pumpkinDepositFrequency.intValue(), TCDefaultValues.pumpkinDepositRarity.intValue(), TCDefaultValues.pumpkinDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, new int[]{DefaultMaterial.GRASS.id}); + // Pumpkin + resource = Resource.create(worldConfig, PlantGen.class, DefaultMaterial.PUMPKIN.id, TCDefaultValues.pumpkinDepositFrequency.intValue(), TCDefaultValues.pumpkinDepositRarity.intValue(), TCDefaultValues.pumpkinDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, DefaultMaterial.GRASS.id); this.ResourceSequence[this.ResourceCount++] = resource; - if (this.DefaultReed > 0) { - //Reed - resource = new Resource(ResourceType.Reed, DefaultMaterial.SUGAR_CANE_BLOCK.id, 0, 0, this.DefaultReed, TCDefaultValues.reedDepositRarity.intValue(), TCDefaultValues.reedDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, new int[]{DefaultMaterial.GRASS.id, DefaultMaterial.DIRT.id, DefaultMaterial.SAND.id}); + // Reed + resource = Resource.create(worldConfig, ReedGen.class, DefaultMaterial.SUGAR_CANE_BLOCK.id, this.DefaultReed, TCDefaultValues.reedDepositRarity.intValue(), TCDefaultValues.reedDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, DefaultMaterial.GRASS.id, DefaultMaterial.DIRT.id, DefaultMaterial.SAND.id); this.ResourceSequence[this.ResourceCount++] = resource; } - if (this.DefaultCactus > 0) { - //Cactus - resource = new Resource(ResourceType.Cactus, DefaultMaterial.CACTUS.id, 0, 0, this.DefaultCactus, TCDefaultValues.cactusDepositRarity.intValue(), TCDefaultValues.cactusDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, new int[]{DefaultMaterial.SAND.id}); + // Cactus + resource = Resource.create(worldConfig, CactusGen.class, DefaultMaterial.CACTUS.id, this.DefaultCactus, TCDefaultValues.cactusDepositRarity.intValue(), TCDefaultValues.cactusDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, DefaultMaterial.SAND.id); this.ResourceSequence[this.ResourceCount++] = resource; } - if (biome == DefaultBiome.JUNGLE || biome == DefaultBiome.JUNGLE_HILLS) // Jungle and Jungle Hills + if (biome == DefaultBiome.JUNGLE || biome == DefaultBiome.JUNGLE_HILLS) { - resource = new Resource(ResourceType.Vines, 0, 0, 0, TCDefaultValues.vinesFrequency.intValue(), TCDefaultValues.vinesRarity.intValue(), TCDefaultValues.vinesMinAltitude.intValue(), this.worldConfig.WorldHeight, new int[]{DefaultMaterial.VINE.id}); + resource = Resource.create(worldConfig, VinesGen.class, TCDefaultValues.vinesFrequency.intValue(), TCDefaultValues.vinesRarity.intValue(), TCDefaultValues.vinesMinAltitude.intValue(), this.worldConfig.WorldHeight, DefaultMaterial.VINE.id); this.ResourceSequence[this.ResourceCount++] = resource; } - //Water source - resource = new Resource(ResourceType.Liquid, DefaultMaterial.WATER.id, 0, 0, TCDefaultValues.waterSourceDepositFrequency.intValue(), TCDefaultValues.waterSourceDepositRarity.intValue(), TCDefaultValues.waterSourceDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, new int[]{DefaultMaterial.STONE.id}); + // Water source + resource = Resource.create(worldConfig, LiquidGen.class, DefaultMaterial.WATER.id, TCDefaultValues.waterSourceDepositFrequency.intValue(), TCDefaultValues.waterSourceDepositRarity.intValue(), TCDefaultValues.waterSourceDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, DefaultMaterial.STONE.id); this.ResourceSequence[this.ResourceCount++] = resource; - //Lava source - resource = new Resource(ResourceType.Liquid, DefaultMaterial.LAVA.id, 0, 0, TCDefaultValues.lavaSourceDepositFrequency.intValue(), TCDefaultValues.lavaSourceDepositRarity.intValue(), TCDefaultValues.lavaSourceDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, new int[]{DefaultMaterial.STONE.id}); + // Lava source + resource = Resource.create(worldConfig, LiquidGen.class, DefaultMaterial.LAVA.id, TCDefaultValues.lavaSourceDepositFrequency.intValue(), TCDefaultValues.lavaSourceDepositRarity.intValue(), TCDefaultValues.lavaSourceDepositMinAltitude.intValue(), this.worldConfig.WorldHeight, DefaultMaterial.STONE.id); this.ResourceSequence[this.ResourceCount++] = resource; - } protected void ReadConfigSettings() @@ -348,7 +355,6 @@ protected void ReadConfigSettings() this.BiomeRivers = ReadModSettings(TCDefaultValues.BiomeRivers.name(), this.DefaultRiver); - this.IsleInBiome = ReadModSettings(TCDefaultValues.IsleInBiome.name(), this.DefaultIsle); this.BiomeIsBorder = ReadModSettings(TCDefaultValues.BiomeIsBorder.name(), this.DefaultBorder); this.NotBorderNear = ReadModSettings(TCDefaultValues.NotBorderNear.name(), this.DefaultNotBorderNear); @@ -364,7 +370,6 @@ protected void ReadConfigSettings() this.SurfaceBlock = ReadModSettings(TCDefaultValues.SurfaceBlock.name(), this.DefaultSurfaceBlock); this.GroundBlock = ReadModSettings(TCDefaultValues.GroundBlock.name(), this.DefaultGroundBlock); - this.UseWorldWaterLevel = ReadSettings(TCDefaultValues.UseWorldWaterLevel); this.waterLevelMax = ReadSettings(TCDefaultValues.WaterLevelMax); this.waterLevelMin = ReadSettings(TCDefaultValues.WaterLevelMin); @@ -389,7 +394,6 @@ protected void ReadConfigSettings() if (DefaultBiome.getBiome(this.Biome.getId()) == null) { // Only for custom biomes - // System.out.println(""Reading mobs for ""+this.Name); // debug this.spawnMonstersAddDefaults = ReadModSettings(""spawnMonstersAddDefaults"", true); this.spawnMonsters = ReadModSettings(""spawnMonsters"", new ArrayList()); this.spawnCreaturesAddDefaults = ReadModSettings(""spawnCreaturesAddDefaults"", true); @@ -487,33 +491,30 @@ private void ReadResourceSettings() for (Map.Entry entry : this.SettingsCache.entrySet()) { String key = entry.getKey(); - for (ResourceType type : ResourceType.values()) + int start = key.indexOf(""(""); + int end = key.lastIndexOf("")""); + if (start != -1 && end != -1) { - if (key.startsWith(type.name())) + String name = key.substring(0, start); + String[] props = ReadComplexString(key.substring(start + 1, end)); + + Resource res = TerrainControl.getResourcesManager().getResource(name, this, Arrays.asList(props)); + + if (res != null) { - int start = key.indexOf(""(""); - int end = key.lastIndexOf("")""); - if (start != -1 && end != -1) + + if (res.getType() == ResourceType.saplingResource) { - Resource res = new Resource(type); - String[] props = ReadComplexString(key.substring(start + 1, end)); - - if (type.Generator.ReadFromString(res, props, this)) - { - if (res.Type == ResourceType.Sapling) - { - if (res.BlockData == -1) - this.SaplingResource = res; - else - this.SaplingTypes[res.BlockData] = res; - - } else - { - LineNumbers.add(Integer.valueOf(entry.getValue())); - this.ResourceSequence[this.ResourceCount++] = res; - } - } else - System.out.println(""TerrainControl: wrong resource "" + type.name() + key); + SaplingGen sapling = (SaplingGen) res; + if (sapling.saplingType == -1) + this.SaplingResource = sapling; + else + this.SaplingTypes[sapling.saplingType] = sapling; + + } else if (res.getType() == ResourceType.biomeConfigResource) + { + LineNumbers.add(Integer.valueOf(entry.getValue())); + this.ResourceSequence[this.ResourceCount++] = res; } } } @@ -541,43 +542,30 @@ private void ReadResourceSettings() private void ReadCustomObjectSettings() { - CustomObjectsCompiled = new ArrayList(); + biomeObjects = new ArrayList(); + biomeObjectStrings = new ArrayList(); // Read from BiomeObjects setting - String customObjectsString = ReadModSettings(""biomeobjects"",""""); - if(customObjectsString.length() > 0) + String biomeObjectsValue = ReadModSettings(""biomeobjects"", """"); + if (biomeObjectsValue.length() > 0) { - String[] customObjects = customObjectsString.split("",""); - for (String customObject : customObjects) + String[] customObjectStrings = biomeObjectsValue.split("",""); + for (String customObjectString : customObjectStrings) { - CustomObjectCompiled object = ObjectsStore.CompileString(customObject, worldConfig.CustomObjectsDirectory); - if (object == null) - object = ObjectsStore.CompileString(customObject, ObjectsStore.GlobalDirectory); + CustomObject object = TerrainControl.getCustomObjectManager().getObjectFromString(customObjectString, worldConfig); if (object != null) - CustomObjectsCompiled.add(object); + { + biomeObjects.add(object); + biomeObjectStrings.add(customObjectString); + } } } - - // Read from random places in BiomeConfig - // TODO: Remove this in 2.4, as it's quite resource intensive - for (Map.Entry entry : this.SettingsCache.entrySet()) - { - CustomObjectCompiled object = ObjectsStore.CompileString(entry.getKey(), worldConfig.CustomObjectsDirectory); - if (object == null) - object = ObjectsStore.CompileString(entry.getKey(), ObjectsStore.GlobalDirectory); - if (object != null) - CustomObjectsCompiled.add(object); - - } - } - protected void WriteConfigSettings() throws IOException { WriteTitle(this.Name + "" biome config""); - WriteComment(""Biome size from 0 to GenerationDepth. Show in what zoom level biome will be generated (see GenerationDepth)""); WriteComment(""Higher numbers=Smaller% of world / Lower numbers=Bigger % of world""); WriteComment(""Don`t work on Ocean and River (frozen versions too) biomes until not added as normal biome.""); @@ -601,7 +589,6 @@ protected void WriteConfigSettings() throws IOException WriteValue(TCDefaultValues.BiomeRivers.name(), this.BiomeRivers); this.WriteNewLine(); - WriteComment(""Biome name list where this biome will be spawned as isle. Like Mushroom isle in Ocean. This work only if this biome is in IsleBiomes in world config""); WriteValue(TCDefaultValues.IsleInBiome.name(), this.IsleInBiome); this.WriteNewLine(); @@ -625,7 +612,6 @@ protected void WriteConfigSettings() throws IOException WriteValue(TCDefaultValues.ReplaceToBiomeName.name(), this.ReplaceBiomeName); this.WriteNewLine(); - WriteTitle(""Terrain Generator Variables""); WriteComment(""BiomeHeight mean how much height will be added in terrain generation""); WriteComment(""It is double value from -10.0 to 10.0""); @@ -668,7 +654,6 @@ protected void WriteConfigSettings() throws IOException WriteComment(""Make empty layer above bedrock layer. ""); WriteHeightSettings(); - this.WriteNewLine(); WriteComment(""Surface block id""); WriteValue(TCDefaultValues.SurfaceBlock.name(), this.SurfaceBlock); @@ -691,7 +676,6 @@ protected void WriteConfigSettings() throws IOException WriteComment(""BlockId used as ice""); WriteValue(TCDefaultValues.IceBlock.name(), this.iceBlock); - this.WriteNewLine(); WriteComment(""Replace Variable: (BlockIdFrom,BlockIdTo[,BlockDataTo,minHeight,maxHeight])""); WriteComment(""Example :""); @@ -713,7 +697,7 @@ protected void WriteConfigSettings() throws IOException this.WriteNewLine(); this.WriteComment(""Biome grass color""); this.WriteColorValue(TCDefaultValues.GrassColor.name(), this.GrassColor); - + this.WriteNewLine(); this.WriteComment(""Whether the grass color is a multiplier""); this.WriteComment(""If you set it to true, the color will be based on this value, the BiomeTemperature and the BiomeWetness""); @@ -786,7 +770,6 @@ protected void WriteConfigSettings() throws IOException this.WriteComment(""These objects will spawn when using the UseBiome keyword.""); this.WriteCustomObjects(); - if (DefaultBiome.getBiome(this.Biome.getId()) != null) { this.WriteTitle(""MOB SPAWNING""); @@ -862,7 +845,6 @@ private void WriteHeightSettings() throws IOException this.WriteValue(TCDefaultValues.CustomHeightControl.name(), output); } - private void WriteModReplaceSettings() throws IOException { if (this.ReplaceCount == 0) @@ -914,22 +896,20 @@ private void WriteModReplaceSettings() throws IOException private void WriteResources() throws IOException { for (int i = 0; i < this.ResourceCount; i++) - this.WriteValue(this.ResourceSequence[i].Type.Generator.WriteToString(this.ResourceSequence[i])); + { + this.WriteValue(this.ResourceSequence[i].makeString()); + } } private void WriteCustomObjects() throws IOException { StringBuilder builder = new StringBuilder(); - for (CustomObjectCompiled objectCompiled : CustomObjectsCompiled) + for (String objectString : biomeObjectStrings) { - builder.append(objectCompiled.Name); - if(!objectCompiled.ChangedSettings.equals("""")) - { - builder.append(""("" + objectCompiled.ChangedSettings + "")""); - } + builder.append(objectString); builder.append(','); } - if(builder.length() > 0) + if (builder.length() > 0) { // Delete last char builder.deleteCharAt(builder.length() - 1); @@ -940,11 +920,11 @@ private void WriteCustomObjects() throws IOException private void WriteSaplingSettings() throws IOException { if (this.SaplingResource != null) - this.WriteValue(ResourceType.Sapling.Generator.WriteToString(this.SaplingResource)); + this.WriteValue(SaplingResource.makeString()); for (Resource res : this.SaplingTypes) if (res != null) - this.WriteValue(ResourceType.Sapling.Generator.WriteToString(res)); + this.WriteValue(res.makeString()); } @@ -976,11 +956,12 @@ protected void CorrectSettings() protected void RenameOldSettings() { // Old values from WorldConfig - TCDefaultValues[] copyFromWorld = {TCDefaultValues.MaxAverageHeight, TCDefaultValues.MaxAverageDepth, TCDefaultValues.Volatility1, TCDefaultValues.Volatility2, TCDefaultValues.VolatilityWeight1, TCDefaultValues.VolatilityWeight2, TCDefaultValues.DisableBiomeHeight, TCDefaultValues.CustomHeightControl}; + TCDefaultValues[] copyFromWorld = { TCDefaultValues.MaxAverageHeight, TCDefaultValues.MaxAverageDepth, TCDefaultValues.Volatility1, TCDefaultValues.Volatility2, TCDefaultValues.VolatilityWeight1, TCDefaultValues.VolatilityWeight2, TCDefaultValues.DisableBiomeHeight, TCDefaultValues.CustomHeightControl }; for (TCDefaultValues value : copyFromWorld) if (this.worldConfig.SettingsCache.containsKey(value.name().toLowerCase())) { - //this.SettingsCache.put(value.name(), this.worldConfig.SettingsCache.get(value.name().toLowerCase())); + // this.SettingsCache.put(value.name(), + // this.worldConfig.SettingsCache.get(value.name().toLowerCase())); this.SettingsCache.put(value.name().toLowerCase(), this.worldConfig.SettingsCache.get(value.name().toLowerCase())); } @@ -994,27 +975,29 @@ protected void RenameOldSettings() } } - + // CustomTreeChance int customTreeChance = 0; // Default value - if(worldConfig.SettingsCache.containsKey(""customtreechance"")) + if (worldConfig.SettingsCache.containsKey(""customtreechance"")) { - try { + try + { customTreeChance = Integer.parseInt(worldConfig.SettingsCache.get(""customtreechance"")); - } catch(NumberFormatException e) { + } catch (NumberFormatException e) + { // Ignore, so leave customTreeChance at 0 } } - if(customTreeChance == 100) + if (customTreeChance == 100) { this.SettingsCache.put(""Sapling(All,UseWorld,100)"", ""-""); } - if(customTreeChance > 0 && customTreeChance < 100) + if (customTreeChance > 0 && customTreeChance < 100) { - this.SettingsCache.put(""Sapling(0,UseWorld,""+customTreeChance+"",BigTree,10,Tree,100)"", ""-""); // Oak - this.SettingsCache.put(""Sapling(1,UseWorld,""+customTreeChance+"",Taiga2,100)"", ""-""); // Redwood - this.SettingsCache.put(""Sapling(2,UseWorld,""+customTreeChance+"",Forest,100)"", ""-""); // Birch - this.SettingsCache.put(""Sapling(3,UseWorld,""+customTreeChance+"",CocoaTree,100)"", ""-""); // Jungle + this.SettingsCache.put(""Sapling(0,UseWorld,"" + customTreeChance + "",BigTree,10,Tree,100)"", ""-""); // Oak + this.SettingsCache.put(""Sapling(1,UseWorld,"" + customTreeChance + "",Taiga2,100)"", ""-""); // Redwood + this.SettingsCache.put(""Sapling(2,UseWorld,"" + customTreeChance + "",Forest,100)"", ""-""); // Birch + this.SettingsCache.put(""Sapling(3,UseWorld,"" + customTreeChance + "",CocoaTree,100)"", ""-""); // Jungle } // ReplacedBlocks @@ -1088,11 +1071,9 @@ protected void RenameOldSettings() this.SettingsCache.put(""ReplacedBlocks"" + "":"" + output.substring(0, output.length() - 1), """"); - } } - private int DefaultTrees = 1; private int DefaultFlowers = 2; private int DefaultGrass = 10; @@ -1128,161 +1109,160 @@ private void InitDefaults() this.DefaultBiomeTemperature = this.Biome.getTemperature(); this.DefaultBiomeWetness = this.Biome.getWetness(); - switch (this.Biome.getId()) { - case 0: - this.DefaultColor = ""0x3333FF""; - break; - case 1: - { - this.DefaultTrees = 0; - this.DefaultFlowers = 4; - this.DefaultGrass = 20; - this.DefaultColor = ""0x999900""; - break; - } - case 2: - { - this.DefaultTrees = 0; - this.DefaultDeadBrush = 4; - this.DefaultGrass = 0; - this.DefaultReed = 10; - this.DefaultCactus = 10; - this.DefaultColor = ""0xFFCC33""; - break; - } - case 3: - this.DefaultColor = ""0x333300""; - break; - case 4: - { - this.DefaultTrees = 10; - this.DefaultGrass = 15; - this.DefaultColor = ""0x00FF00""; - break; - } - case 5: - { - this.DefaultTrees = 10; - this.DefaultGrass = 10; - this.DefaultColor = ""0x007700""; - break; - } - case 6: - { - this.DefaultTrees = 2; - this.DefaultFlowers = -999; - this.DefaultDeadBrush = 1; - this.DefaultMushroom = 8; - this.DefaultReed = 10; - this.DefaultClay = 1; - this.DefaultWaterLily = 1; - this.DefaultColor = ""0x99CC66""; - this.DefaultWaterColorMultiplier = ""0xe0ffae""; - this.DefaultGrassColor = ""0x7E6E7E""; - this.DefaultFoliageColor = ""0x7E6E7E""; - break; - } - case 7: - this.DefaultSize = 8; - this.DefaultRarity = 95; - this.DefaultIsle.add(DefaultBiome.SWAMPLAND.Name); - this.DefaultColor = ""0x00CCCC""; - case 8: - case 9: - - break; - case 10: - this.DefaultColor = ""0xFFFFFF""; - break; - case 11: - this.DefaultColor = ""0x66FFFF""; - break; - case 12: - this.DefaultColor = ""0xCCCCCC""; - break; - case 13: - this.DefaultColor = ""0xCC9966""; - break; - case 14: - { - this.DefaultSurfaceBlock = (byte) DefaultMaterial.MYCEL.id; - this.DefaultMushroom = 1; - this.DefaultGrass = 0; - this.DefaultFlowers = 0; - this.DefaultTrees = 0; - this.DefaultRarity = 1; - this.DefaultRiver = false; - this.DefaultSize = 6; - this.DefaultIsle.add(DefaultBiome.OCEAN.Name); - this.DefaultColor = ""0xFF33CC""; - this.DefaultWaterLily = 1; - break; - } - case 15: - { - this.DefaultRiver = false; - this.DefaultSize = 9; - this.DefaultBorder.add(DefaultBiome.MUSHROOM_ISLAND.Name); - this.DefaultColor = ""0xFF9999""; - break; - } - case 16: - this.DefaultTrees = 0; - this.DefaultSize = 8; - this.DefaultBorder.add(DefaultBiome.OCEAN.Name); - this.DefaultNotBorderNear.add(DefaultBiome.RIVER.Name); - this.DefaultNotBorderNear.add(DefaultBiome.SWAMPLAND.Name); - this.DefaultNotBorderNear.add(DefaultBiome.EXTREME_HILLS.Name); - this.DefaultNotBorderNear.add(DefaultBiome.MUSHROOM_ISLAND.Name); - this.DefaultColor = ""0xFFFF00""; - break; - case 17: - this.DefaultSize = 6; - this.DefaultRarity = 97; - this.DefaultIsle.add(DefaultBiome.DESERT.Name); - this.DefaultTrees = 0; - this.DefaultDeadBrush = 4; - this.DefaultGrass = 0; - this.DefaultReed = 50; - this.DefaultCactus = 10; - this.DefaultColor = ""0x996600""; - break; - case 18: - this.DefaultSize = 6; - this.DefaultRarity = 97; - this.DefaultIsle.add(DefaultBiome.FOREST.Name); - this.DefaultTrees = 10; - this.DefaultGrass = 15; - this.DefaultColor = ""0x009900""; - break; - case 19: - this.DefaultSize = 6; - this.DefaultRarity = 97; - this.DefaultIsle.add(DefaultBiome.TAIGA.Name); - this.DefaultTrees = 10; - this.DefaultGrass = 10; - this.DefaultColor = ""0x003300""; - break; - case 20: - this.DefaultSize = 8; - this.DefaultBorder.add(DefaultBiome.EXTREME_HILLS.Name); - this.DefaultColor = ""0x666600""; - break; - case 21: - this.DefaultTrees = 50; - this.DefaultGrass = 25; - this.DefaultFlowers = 4; - this.DefaultColor = ""0xCC6600""; - break; - case 22: - this.DefaultTrees = 50; - this.DefaultGrass = 25; - this.DefaultFlowers = 4; - this.DefaultColor = ""0x663300""; - this.DefaultIsle.add(DefaultBiome.JUNGLE.Name); - break; + case 0: + this.DefaultColor = ""0x3333FF""; + break; + case 1: + { + this.DefaultTrees = 0; + this.DefaultFlowers = 4; + this.DefaultGrass = 20; + this.DefaultColor = ""0x999900""; + break; + } + case 2: + { + this.DefaultTrees = 0; + this.DefaultDeadBrush = 4; + this.DefaultGrass = 0; + this.DefaultReed = 10; + this.DefaultCactus = 10; + this.DefaultColor = ""0xFFCC33""; + break; + } + case 3: + this.DefaultColor = ""0x333300""; + break; + case 4: + { + this.DefaultTrees = 10; + this.DefaultGrass = 15; + this.DefaultColor = ""0x00FF00""; + break; + } + case 5: + { + this.DefaultTrees = 10; + this.DefaultGrass = 10; + this.DefaultColor = ""0x007700""; + break; + } + case 6: + { + this.DefaultTrees = 2; + this.DefaultFlowers = -999; + this.DefaultDeadBrush = 1; + this.DefaultMushroom = 8; + this.DefaultReed = 10; + this.DefaultClay = 1; + this.DefaultWaterLily = 1; + this.DefaultColor = ""0x99CC66""; + this.DefaultWaterColorMultiplier = ""0xe0ffae""; + this.DefaultGrassColor = ""0x7E6E7E""; + this.DefaultFoliageColor = ""0x7E6E7E""; + break; + } + case 7: + this.DefaultSize = 8; + this.DefaultRarity = 95; + this.DefaultIsle.add(DefaultBiome.SWAMPLAND.Name); + this.DefaultColor = ""0x00CCCC""; + case 8: + case 9: + + break; + case 10: + this.DefaultColor = ""0xFFFFFF""; + break; + case 11: + this.DefaultColor = ""0x66FFFF""; + break; + case 12: + this.DefaultColor = ""0xCCCCCC""; + break; + case 13: + this.DefaultColor = ""0xCC9966""; + break; + case 14: + { + this.DefaultSurfaceBlock = (byte) DefaultMaterial.MYCEL.id; + this.DefaultMushroom = 1; + this.DefaultGrass = 0; + this.DefaultFlowers = 0; + this.DefaultTrees = 0; + this.DefaultRarity = 1; + this.DefaultRiver = false; + this.DefaultSize = 6; + this.DefaultIsle.add(DefaultBiome.OCEAN.Name); + this.DefaultColor = ""0xFF33CC""; + this.DefaultWaterLily = 1; + break; + } + case 15: + { + this.DefaultRiver = false; + this.DefaultSize = 9; + this.DefaultBorder.add(DefaultBiome.MUSHROOM_ISLAND.Name); + this.DefaultColor = ""0xFF9999""; + break; + } + case 16: + this.DefaultTrees = 0; + this.DefaultSize = 8; + this.DefaultBorder.add(DefaultBiome.OCEAN.Name); + this.DefaultNotBorderNear.add(DefaultBiome.RIVER.Name); + this.DefaultNotBorderNear.add(DefaultBiome.SWAMPLAND.Name); + this.DefaultNotBorderNear.add(DefaultBiome.EXTREME_HILLS.Name); + this.DefaultNotBorderNear.add(DefaultBiome.MUSHROOM_ISLAND.Name); + this.DefaultColor = ""0xFFFF00""; + break; + case 17: + this.DefaultSize = 6; + this.DefaultRarity = 97; + this.DefaultIsle.add(DefaultBiome.DESERT.Name); + this.DefaultTrees = 0; + this.DefaultDeadBrush = 4; + this.DefaultGrass = 0; + this.DefaultReed = 50; + this.DefaultCactus = 10; + this.DefaultColor = ""0x996600""; + break; + case 18: + this.DefaultSize = 6; + this.DefaultRarity = 97; + this.DefaultIsle.add(DefaultBiome.FOREST.Name); + this.DefaultTrees = 10; + this.DefaultGrass = 15; + this.DefaultColor = ""0x009900""; + break; + case 19: + this.DefaultSize = 6; + this.DefaultRarity = 97; + this.DefaultIsle.add(DefaultBiome.TAIGA.Name); + this.DefaultTrees = 10; + this.DefaultGrass = 10; + this.DefaultColor = ""0x003300""; + break; + case 20: + this.DefaultSize = 8; + this.DefaultBorder.add(DefaultBiome.EXTREME_HILLS.Name); + this.DefaultColor = ""0x666600""; + break; + case 21: + this.DefaultTrees = 50; + this.DefaultGrass = 25; + this.DefaultFlowers = 4; + this.DefaultColor = ""0xCC6600""; + break; + case 22: + this.DefaultTrees = 50; + this.DefaultGrass = 25; + this.DefaultFlowers = 4; + this.DefaultColor = ""0x663300""; + this.DefaultIsle.add(DefaultBiome.JUNGLE.Name); + break; } } diff --git a/common/src/com/khorn/terraincontrol/configuration/ConfigFile.java b/common/src/com/khorn/terraincontrol/configuration/ConfigFile.java index 93e688b2a..7ef4da5a4 100644 --- a/common/src/com/khorn/terraincontrol/configuration/ConfigFile.java +++ b/common/src/com/khorn/terraincontrol/configuration/ConfigFile.java @@ -8,6 +8,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Map; public abstract class ConfigFile { @@ -15,7 +16,7 @@ public abstract class ConfigFile // TODO: This map is populated with lowercase versions as well. // TODO: That is a derped approach. Use TreeSet with CASE_INSENSITIVE_ORDER instead. - protected HashMap SettingsCache = new HashMap(); + protected Map SettingsCache = new HashMap(); // TODO: We should use GSON only instead of just for a few fields. // TODO: Hah. We should remove that buggy GSON. diff --git a/common/src/com/khorn/terraincontrol/configuration/Resource.java b/common/src/com/khorn/terraincontrol/configuration/Resource.java index 5169b3f42..569fe97e3 100644 --- a/common/src/com/khorn/terraincontrol/configuration/Resource.java +++ b/common/src/com/khorn/terraincontrol/configuration/Resource.java @@ -1,99 +1,258 @@ package com.khorn.terraincontrol.configuration; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + import com.khorn.terraincontrol.DefaultMaterial; -import com.khorn.terraincontrol.customobjects.CustomObjectCompiled; +import com.khorn.terraincontrol.LocalWorld; +import com.khorn.terraincontrol.TerrainControl; +import com.khorn.terraincontrol.exception.InvalidResourceException; import com.khorn.terraincontrol.generator.resourcegens.ResourceType; -import com.khorn.terraincontrol.generator.resourcegens.TreeType; -public class Resource +public abstract class Resource { - public ResourceType Type; - public int MinAltitude; - public int MaxAltitude; - public int MinSize; - public int MaxSize; - public int BlockId; - public int BlockData; - public int[] SourceBlockId = new int[0]; - public int Frequency; - public int Rarity; - public TreeType[] TreeTypes = new TreeType[0]; - public int[] TreeChances = new int[0]; - - // For custom trees - public CustomObjectCompiled[] CUObjectsWorld = new CustomObjectCompiled[0]; - public CustomObjectCompiled[] CUObjectsBiome = new CustomObjectCompiled[0]; - - public CustomObjectCompiled[] CUObjects = new CustomObjectCompiled[0]; - public String[] CUObjectsNames = new String[0]; - - - public Resource(ResourceType type) + protected int frequency; + protected int rarity; + protected WorldConfig worldConfig; + + /** + * Sets the world. Needed for some resources, like CustomObject and Tree. + * @param world + */ + public void setWorldConfig(WorldConfig worldConfig) { - Type = type; + this.worldConfig = worldConfig; } - - public Resource(ResourceType type, int blockId, int blockData, int size, int frequency, int rarity, int minAltitude, int maxAltitude, int[] sourceBlockIds) + + /** + * Convenience method for creating a resource. Used to create the default resources. + * @param world + * @param clazz + * @param args + * @return + */ + public static Resource create(WorldConfig config, Class clazz, Object... args) { - this.Type = type; - this.BlockId = blockId; - this.BlockData = blockData; - this.MaxSize = size; - this.Frequency = frequency; - this.Rarity = rarity; - this.MinAltitude = minAltitude; - this.MaxAltitude = maxAltitude; - this.SourceBlockId = sourceBlockIds; + List stringArgs = new ArrayList(args.length); + for(Object arg: args) + { + stringArgs.add("""" + arg); + } + + Resource resource; + try + { + resource = clazz.newInstance(); + } catch (InstantiationException e) + { + return null; + } catch (IllegalAccessException e) + { + return null; + } + resource.setWorldConfig(config); + try { + resource.load(stringArgs); + } catch(InvalidResourceException e) + { + TerrainControl.log(""Invalid default resource! Please report! "" + clazz.getName() + "": ""+e.getMessage()); + e.printStackTrace(); + } + + return resource; } - public Resource(ResourceType type, int minSize, int maxSize, int frequency, int rarity, int minAltitude, int maxAltitude) + /** + * Loads the settings. Returns false if one of the arguments contains an + * error. + * + * @param args + * List of args. + * @return Returns false if one of the arguments contains an error, + * otherwise true. + * @throws InvalidResourceException + * If the resoure is invalid. + */ + public abstract void load(List args) throws InvalidResourceException; + + /** + * Spawns the resource at this position, ignoring rarity and frequency. + * + * @param world + * @param chunkX + * @param chunkZ + */ + public abstract void spawn(LocalWorld world, Random random, int x, int z); + + /** + * Spawns the resource normally. + * + * @param world + * @param chunkX + * @param chunkZ + */ + public void process(LocalWorld world, Random random, int chunkX, int chunkZ) { - this.Type = type; - this.MaxSize = maxSize; - this.MinSize = minSize; - this.Frequency = frequency; - this.Rarity = rarity; - this.MinAltitude = minAltitude; - this.MaxAltitude = maxAltitude; + for (int t = 0; t < frequency; t++) + { + if (random.nextInt(100) > rarity) + continue; + int x = chunkX * 16 + random.nextInt(16) + 8; + int z = chunkZ * 16 + random.nextInt(16) + 8; + spawn(world, random, x, z); + } } - public Resource(ResourceType type, int blockId, int frequency, int rarity, int minAltitude, int maxAltitude) + /** + * Gets the type of this resource. + * + * @return The type of this resource. + */ + public abstract ResourceType getType(); + + /** + * Gets a String representation, like Tree(10,BigTree,50,Tree,100) + * + * @return A String representation, like Tree(10,BigTree,50,Tree,100) + */ + public abstract String makeString(); + + /** + * Parses the string and returns a number between minValue and maxValue. + * Returns Resource.INCORRECT_NUMBER if the string is not a number. + * + * @param string + * @param minValue + * @param maxValue + * @return + * @throws InvalidResourceException + * If the number is invalid. + */ + public int getInt(String string, int minValue, int maxValue) throws InvalidResourceException { - this.Type = type; - this.BlockId = blockId; - this.Frequency = frequency; - this.Rarity = rarity; - this.MinAltitude = minAltitude; - this.MaxAltitude = maxAltitude; + try + { + int number = Integer.parseInt(string); + if (number < minValue) + { + return minValue; + } + if (number > maxValue) + { + return maxValue; + } + return number; + } catch (NumberFormatException e) + { + throw new InvalidResourceException(""Incorrect number: "" + string); + } } - public Resource(ResourceType type, int frequency, TreeType[] types, int[] treeChances) + /** + * Returns the block id with the given name. + * + * @param string + * @return + */ + public int getBlockId(String string) throws InvalidResourceException { - this.Type = type; - this.Frequency = frequency; - if (types != null) + if (string.indexOf('.') != -1) + { + // Ignore block data + string = string.split(""\\."")[0]; + } + + DefaultMaterial material = DefaultMaterial.getMaterial(string); + if (material != null) { - this.TreeTypes = types; - this.TreeChances = treeChances; + return material.id; } + + return getInt(string, 0, 256); } - public boolean CheckSourceId(int blockId) + /** + * Gets the block data from a material string. + * + * @param string + * @return + * @throws InvalidResourceException + */ + public int getBlockData(String string) throws InvalidResourceException { - for (int id : this.SourceBlockId) - if (blockId == id) - return true; - return false; + if (string.indexOf('.') == -1) + { + // No block data + return 0; + } + + // Get block data + string = string.split(""\\."")[1]; + return getInt(string, 0, 16); } + public void assureSize(int size, List args) throws InvalidResourceException + { + if (args.size() < size) + { + throw new InvalidResourceException(""Too few arguments supplied""); + } + } - public String BlockIdToName(int id) + /** + * Gets the material name back from the id and data. + * + * @param id + * The block id + * @param data + * The block data + * @return String in the format blockname[.blockdata] + */ + public String makeMaterial(int id, int data) { + String materialString = """" + id; DefaultMaterial material = DefaultMaterial.getMaterial(id); if (material != DefaultMaterial.UNKNOWN_BLOCK) - return material.name(); - else - return Integer.toString(id); + { + // No name, return number as String + materialString = material.toString(); + } + + if (data > 0) + { + materialString = materialString + ""."" + data; + } + + return materialString; } + /** + * Gets the material name back from the id. + * + * @param id + * The block id + * @return String in the format blockname + */ + public String makeMaterial(int id) + { + return makeMaterial(id, 0); + } + + /** + * Returns a String in the format "",materialName,materialName,etc"" + * + * @param ids + * @return + */ + public String makeMaterial(List ids) + { + String string = """"; + for (int blockId : ids) + { + string += "",""; + string += makeMaterial(blockId); + } + return string; + } } diff --git a/common/src/com/khorn/terraincontrol/configuration/WorldConfig.java b/common/src/com/khorn/terraincontrol/configuration/WorldConfig.java index a25695090..b7fbf0fac 100644 --- a/common/src/com/khorn/terraincontrol/configuration/WorldConfig.java +++ b/common/src/com/khorn/terraincontrol/configuration/WorldConfig.java @@ -3,9 +3,8 @@ import com.khorn.terraincontrol.DefaultBiome; import com.khorn.terraincontrol.LocalBiome; import com.khorn.terraincontrol.LocalWorld; +import com.khorn.terraincontrol.TerrainControl; import com.khorn.terraincontrol.customobjects.CustomObject; -import com.khorn.terraincontrol.customobjects.CustomObjectCompiled; -import com.khorn.terraincontrol.customobjects.ObjectsStore; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -13,13 +12,19 @@ import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; +import java.util.Map; public class WorldConfig extends ConfigFile { + public LocalWorld world; + public ArrayList CustomBiomes = new ArrayList(); public HashMap CustomBiomeIds = new HashMap(); - public ArrayList CustomObjectsCompiled; + /** + * Holds all world CustomObjects. All keys should be lowercase. + */ + public Map customObjects = new HashMap(); public ArrayList NormalBiomes = new ArrayList(); public ArrayList IceBiomes = new ArrayList(); @@ -32,10 +37,6 @@ public class WorldConfig extends ConfigFile public byte[] ReplaceMatrixBiomes = new byte[256]; public boolean HaveBiomeReplace = false; - // public BiomeBase currentBiome; - // --Commented out by Inspection (17.07.11 1:49):String seedValue; - - // For old biome generator public double oldBiomeSize; @@ -161,6 +162,7 @@ public WorldConfig(File settingsDir, LocalWorld world, boolean checkOnly) { this.SettingsDir = settingsDir; this.WorldName = world.getName(); + this.world = world; File settingsFile = new File(this.SettingsDir, TCDefaultValues.WorldSettingsName.stringValue()); @@ -285,15 +287,9 @@ private void ReadWorldCustomObjects() } } - ArrayList rawObjects = ObjectsStore.LoadObjectsFromDirectory(CustomObjectsDirectory); - - - CustomObjectsCompiled = new ArrayList(); - - for (CustomObject object : rawObjects) - CustomObjectsCompiled.add(object.Compile("""")); - System.out.println(""TerrainControl: "" + CustomObjectsCompiled.size() + "" world custom objects loaded""); + customObjects = TerrainControl.getCustomObjectManager().loadObjects(CustomObjectsDirectory); + TerrainControl.log(customObjects.size() + "" world custom objects loaded""); } diff --git a/common/src/com/khorn/terraincontrol/customobjects/CustomObject.java b/common/src/com/khorn/terraincontrol/customobjects/CustomObject.java index bdb8e3347..a7394627a 100644 --- a/common/src/com/khorn/terraincontrol/customobjects/CustomObject.java +++ b/common/src/com/khorn/terraincontrol/customobjects/CustomObject.java @@ -1,101 +1,123 @@ -package com.khorn.terraincontrol.customobjects; - - -import com.khorn.terraincontrol.configuration.ConfigFile; - -import java.io.File; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -public class CustomObject extends ConfigFile -{ - public boolean IsValid = false; - public File FilePath; - public String Name = """"; - - public CustomObject(File objectFile) - { - FilePath = objectFile; - Name = objectFile.getName(); - - if(!Name.toLowerCase().endsWith(BODefaultValues.BO_Extension.stringValue().toLowerCase())) - return; - - //Remove extension. - Name = Name.substring(0, Name.length() - 4); - - - ReadSettingsFile(objectFile); - CorrectSettings(); - if (SettingsCache.containsKey(""[META]"") && SettingsCache.containsKey(""[DATA]"")) - this.IsValid = true; - - if (!this.IsValid) - return; - - ReadConfigSettings(); - } - - public CustomObjectCompiled Compile(String settingsLine) - { - HashMap newSettings = new HashMap(); - for (Map.Entry entry : this.SettingsCache.entrySet()) - if (BODefaultValues.Contains(entry.getKey()) || ObjectCoordinate.isCoordinateString(entry.getKey())) - newSettings.put(entry.getKey(), entry.getValue()); - - String[] keys = settingsLine.split("";""); - String changedSettings = """"; - boolean first = true; - - for (String key : keys) - { - String[] values = null; - if (key.contains(""="")) - values = key.split(""="", 2); - else if (key.contains("":"")) - values = key.split(""="", 2); - if (values == null) - continue; - if (BODefaultValues.Contains(values[0].toLowerCase()) || ObjectCoordinate.isCoordinateString(values[0])) - { - newSettings.put(values[0].toLowerCase(), values[1]); - changedSettings = changedSettings + (first ? """" : "";"") + key; - if (first) - first = false; - } - } - - return new CustomObjectCompiled(newSettings, Name, changedSettings, this); - - } - - @Override - public boolean sayNotFoundEnabled() - { - return false; - } - - @Override - protected void ReadConfigSettings() - { - - } - - @Override - protected void WriteConfigSettings() throws IOException - { - - } - - @Override - protected void CorrectSettings() - { - - } - - @Override - protected void RenameOldSettings() - { - } -} +package com.khorn.terraincontrol.customobjects; + +import java.util.Map; +import java.util.Random; + +import com.khorn.terraincontrol.LocalBiome; +import com.khorn.terraincontrol.LocalWorld; + +public interface CustomObject +{ + /** + * Returns the name of this object. + * + * @return + */ + public String getName(); + + /** + * Returns whether this object can spawn as a tree. UseWorld and UseBiome + * should return true. + * + * @return Whether this object can spawn as a tree. + */ + public boolean canSpawnAsTree(); + + /** + * Returns whether this object can spawn from the CustomObject() resource. + * Vanilla trees should return false; everything else should return true. + * + * @return + */ + public boolean canSpawnAsObject(); + + /** + * Spawns the object at the given position. + * + * @param world + * @param x + * @param y + * @param z + * @return Whether the attempt was successful. + */ + public boolean spawn(LocalWorld world, Random random, int x, int y, int z); + + /** + * Spawns the object at the given position. If the object isn't a tree, it + * shouldn't spawn and it should return false. + * + * @param world + * @param x + * @param y + * @param z + * @return Whether the attempt was successful. + */ + public boolean spawnAsTree(LocalWorld world, Random random, int x, int y, int z); + + /** + * Spawns the object at the given position. It should search a suitable y + * location by itself. + * + * @param world + * @param x + * @param y + * @param z + * @return Whether the attempt was successful. + */ + public boolean spawn(LocalWorld world, Random random, int x, int z); + + /** + * Spawns the object at the given position. It should search a suitable y + * location by itself. If the object isn't a tree, it shouldn't spawn and it + * should return false. + * + * @param world + * @param x + * @param y + * @param z + * @return Whether the attempt was successful. + */ + public boolean spawnAsTree(LocalWorld world, Random random, int x, int z); + + /** + * Spawns the object in a chunk. The object can search a good y position by + * itself. + * + * @param world + * @param random + * @param chunkX + * @param chunkZ + */ + public void process(LocalWorld world, Random random, int chunkX, int chunkZ); + + /** + * Spawns the object in a chunk. The object can search a good y position by + * itself. If the object isn't a tree, the object shouldn't spawn and it + * should return false. + * + * @param world + * @param random + * @param x + * @param z + */ + public void processAsTree(LocalWorld world, Random random, int chunkX, int chunkZ); + + /** + * Returns a copy of this object will all the settings applied. Can return + * null if the settings are invalid. + * + * @param settings + * A Map with all the settings. + * @return A copy of this object will all the settings applied. + */ + public CustomObject applySettings(Map settings); + + /** + * Returns whether this object would like to spawn in this biome. BO2s will + * return whether this biome is in their spawnInBiome setting. + * + * @param biome + * @return + */ + public boolean hasPreferenceToSpawnIn(LocalBiome biome); +} diff --git a/common/src/com/khorn/terraincontrol/customobjects/CustomObjectCompiled.java b/common/src/com/khorn/terraincontrol/customobjects/CustomObjectCompiled.java deleted file mode 100644 index 032cf215c..000000000 --- a/common/src/com/khorn/terraincontrol/customobjects/CustomObjectCompiled.java +++ /dev/null @@ -1,229 +0,0 @@ -package com.khorn.terraincontrol.customobjects; - -import com.khorn.terraincontrol.DefaultMaterial; -import com.khorn.terraincontrol.configuration.ConfigFile; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; - -public class CustomObjectCompiled extends ConfigFile -{ - public ObjectCoordinate[][] Data = new ObjectCoordinate[4][]; - - public CustomObjectCompiled[] GroupObjects = null; - - public String Name; - - public HashSet SpawnInBiome; - - public String Version; - public HashSet SpawnOnBlockType; - - public HashSet CollisionBlockType; - - public boolean SpawnWater; - public boolean SpawnLava; - public boolean SpawnAboveGround; - public boolean SpawnUnderGround; - - public boolean SpawnSunlight; - public boolean SpawnDarkness; - - public boolean UnderFill; - public boolean RandomRotation; - public boolean Dig; - public boolean Tree; - public boolean Branch; - public boolean DiggingBranch; - public boolean NeedsFoundation; - public int Rarity; - public double CollisionPercentage; - public int SpawnElevationMin; - public int SpawnElevationMax; - - public int GroupFrequencyMin; - public int GroupFrequencyMax; - public int GroupSeparationMin; - public int GroupSeparationMax; - public String GroupId; - - public int BranchLimit; - - public String ChangedSettings; - - public CustomObject parent; - - public CustomObjectCompiled(HashMap settings, String name, String changedSettings, CustomObject parent) - { - SettingsCache = settings; - this.Name = name; - this.ChangedSettings = changedSettings; - this.parent = parent; - - ReadConfigSettings(); - CorrectSettings(); - - SettingsCache.clear(); - SettingsCache = null; - } - - - public boolean CheckBiome(String biomeName) - { - return (SpawnInBiome.contains(BODefaultValues.BO_ALL_KEY.stringValue()) || SpawnInBiome.contains(BODefaultValues.BO_ALL_KEY.stringValue().toLowerCase()) || SpawnInBiome.contains(biomeName)); - } - - - @Override - protected void ReadConfigSettings() - { - this.Version = ReadModSettings(BODefaultValues.version.name(), BODefaultValues.version.stringValue()); - - - this.SpawnOnBlockType = this.ReadBlockList(ReadModSettings(BODefaultValues.spawnOnBlockType.name(), BODefaultValues.spawnOnBlockType.StringArrayListValue()),BODefaultValues.spawnOnBlockType.name()); - this.CollisionBlockType = this.ReadBlockList(ReadModSettings(BODefaultValues.collisionBlockType.name(), BODefaultValues.collisionBlockType.StringArrayListValue()),BODefaultValues.collisionBlockType.name()); - - this.SpawnInBiome = new HashSet(ReadModSettings(BODefaultValues.spawnInBiome.name(), BODefaultValues.spawnInBiome.StringArrayListValue())); - - - this.SpawnSunlight = ReadModSettings(BODefaultValues.spawnSunlight.name(), BODefaultValues.spawnSunlight.booleanValue()); - this.SpawnDarkness = ReadModSettings(BODefaultValues.spawnDarkness.name(), BODefaultValues.spawnDarkness.booleanValue()); - this.SpawnWater = ReadModSettings(BODefaultValues.spawnWater.name(), BODefaultValues.spawnWater.booleanValue()); - this.SpawnLava = ReadModSettings(BODefaultValues.spawnLava.name(), BODefaultValues.spawnLava.booleanValue()); - this.SpawnAboveGround = ReadModSettings(BODefaultValues.spawnAboveGround.name(), BODefaultValues.spawnAboveGround.booleanValue()); - this.SpawnUnderGround = ReadModSettings(BODefaultValues.spawnUnderGround.name(), BODefaultValues.spawnUnderGround.booleanValue()); - - this.UnderFill = ReadModSettings(BODefaultValues.underFill.name(), BODefaultValues.underFill.booleanValue()); - - this.RandomRotation = ReadModSettings(BODefaultValues.randomRotation.name(), BODefaultValues.randomRotation.booleanValue()); - this.Dig = ReadModSettings(BODefaultValues.dig.name(), BODefaultValues.dig.booleanValue()); - this.Tree = ReadModSettings(BODefaultValues.tree.name(), BODefaultValues.tree.booleanValue()); - this.Branch = ReadModSettings(BODefaultValues.branch.name(), BODefaultValues.branch.booleanValue()); - this.DiggingBranch = ReadModSettings(BODefaultValues.diggingBranch.name(), BODefaultValues.diggingBranch.booleanValue()); - this.NeedsFoundation = ReadModSettings(BODefaultValues.needsFoundation.name(), BODefaultValues.needsFoundation.booleanValue()); - this.Rarity = ReadModSettings(BODefaultValues.rarity.name(), BODefaultValues.rarity.intValue()); - this.CollisionPercentage = ReadModSettings(BODefaultValues.collisionPercentage.name(), BODefaultValues.collisionPercentage.intValue()); - this.SpawnElevationMin = ReadModSettings(BODefaultValues.spawnElevationMin.name(), BODefaultValues.spawnElevationMin.intValue()); - this.SpawnElevationMax = ReadModSettings(BODefaultValues.spawnElevationMax.name(), BODefaultValues.spawnElevationMax.intValue()); - - this.GroupFrequencyMin = ReadModSettings(BODefaultValues.groupFrequencyMin.name(), BODefaultValues.groupFrequencyMin.intValue()); - this.GroupFrequencyMax = ReadModSettings(BODefaultValues.groupFrequencyMax.name(), BODefaultValues.groupFrequencyMax.intValue()); - this.GroupSeparationMin = ReadModSettings(BODefaultValues.groupSeperationMin.name(), BODefaultValues.groupSeperationMin.intValue()); - this.GroupSeparationMax = ReadModSettings(BODefaultValues.groupSeperationMax.name(), BODefaultValues.groupSeperationMax.intValue()); - this.GroupId = ReadModSettings(BODefaultValues.groupId.name(), BODefaultValues.groupId.stringValue()); - - - this.BranchLimit = ReadModSettings(BODefaultValues.branchLimit.name(), BODefaultValues.branchLimit.intValue()); - - this.ReadCoordinates(); - } - - @Override - protected boolean sayNotFoundEnabled() - { - return false; - } - - @Override - protected void CorrectSettings() - { - - - } - - @Override - protected void WriteConfigSettings() throws IOException - { - - } - - @Override - protected void RenameOldSettings() - { - - } - - - private void ReadCoordinates() - { - ArrayList coordinates = new ArrayList(); - - for (String key : SettingsCache.keySet()) - { - ObjectCoordinate buffer = ObjectCoordinate.getCoordinateFromString(key, SettingsCache.get(key)); - if (buffer != null) - coordinates.add(buffer); - } - - Data[0] = new ObjectCoordinate[coordinates.size()]; - Data[1] = new ObjectCoordinate[coordinates.size()]; - Data[2] = new ObjectCoordinate[coordinates.size()]; - Data[3] = new ObjectCoordinate[coordinates.size()]; - - for (int i = 0; i < coordinates.size(); i++) - { - ObjectCoordinate coordinate = coordinates.get(i); - - Data[0][i] = coordinate; - coordinate = coordinate.Rotate(); - Data[1][i] = coordinate; - coordinate = coordinate.Rotate(); - Data[2][i] = coordinate; - coordinate = coordinate.Rotate(); - Data[3][i] = coordinate; - } - - - } - - private HashSet ReadBlockList(ArrayList blocks, String settingName) - { - HashSet output = new HashSet(); - - boolean nonIntegerValues = false; - boolean all = false; - boolean solid = false; - - for (String block : blocks) - { - - if (block.equals(BODefaultValues.BO_ALL_KEY.stringValue())) - { - all = true; - continue; - } - if (block.equals(BODefaultValues.BO_SolidKey.stringValue())) - { - solid = true; - continue; - } - try - { - int blockID = Integer.decode(block); - if (blockID != 0) - output.add(blockID); - } catch (NumberFormatException e) - { - nonIntegerValues = true; - } - } - - if (all || solid) - for (DefaultMaterial material : DefaultMaterial.values()) - { - if(material.id == 0) - continue; - if (solid && !material.isSolid()) - continue; - output.add(material.id); - - } - if (nonIntegerValues) - System.out.println(""TerrainControl: Custom object "" + this.Name + "" have wrong value "" + settingName); - - return output; - - } -} diff --git a/common/src/com/khorn/terraincontrol/customobjects/CustomObjectGen.java b/common/src/com/khorn/terraincontrol/customobjects/CustomObjectGen.java deleted file mode 100644 index 06acaad21..000000000 --- a/common/src/com/khorn/terraincontrol/customobjects/CustomObjectGen.java +++ /dev/null @@ -1,344 +0,0 @@ -package com.khorn.terraincontrol.customobjects; - -import com.khorn.terraincontrol.DefaultMaterial; -import com.khorn.terraincontrol.LocalWorld; -import com.khorn.terraincontrol.configuration.BiomeConfig; -import com.khorn.terraincontrol.configuration.Resource; -import com.khorn.terraincontrol.generator.resourcegens.ResourceGenBase; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Random; - -public class CustomObjectGen extends ResourceGenBase -{ - - - @Override - public void Process(LocalWorld world, Random rand, Resource res, int _x, int _z) - { - - if (res.CUObjects.length == 0) - return; - - _x = _x + 8; - _z = _z + 8; - - boolean objectSpawned = false; - int spawnAttempts = 0; - while (!objectSpawned) - { - if (spawnAttempts > world.getSettings().objectSpawnRatio) - return; - - spawnAttempts++; - - CustomObjectCompiled SelectedObject = res.CUObjects[rand.nextInt(res.CUObjects.length)]; - if (SelectedObject.Branch) - continue; - - int randomRoll = rand.nextInt(100); - int ObjectRarity = SelectedObject.Rarity; - - while (randomRoll < ObjectRarity) - { - ObjectRarity -= 100; - - int x = _x + rand.nextInt(16); - int z = _z + rand.nextInt(16); - int y; - - if (SelectedObject.SpawnAboveGround) - y = world.getSolidHeight(x, z); - else if (SelectedObject.SpawnUnderGround) - { - int solidHeight = world.getSolidHeight(x, z); - if (solidHeight < 1 || solidHeight <= SelectedObject.SpawnElevationMin) - continue; - if (solidHeight > SelectedObject.SpawnElevationMax) - solidHeight = SelectedObject.SpawnElevationMax; - y = rand.nextInt(solidHeight - SelectedObject.SpawnElevationMin) + SelectedObject.SpawnElevationMin; - } else - y = world.getHighestBlockYAt(x, z); - - if (y < 0) - continue; - - if (!ObjectCanSpawn(world, x, y, z, SelectedObject)) - continue; - - - objectSpawned = GenerateCustomObject(world, rand, x, y, z, SelectedObject); - - if (objectSpawned) - GenerateCustomObjectFromGroup(world, rand, x, y, z, SelectedObject); - } - } - - - } - - public static void GenerateCustomObjectFromGroup(LocalWorld world, Random rand, int x, int y, int z, CustomObjectCompiled workObject) - { - if (workObject.GroupObjects == null) - return; - - int attempts = 3; - if ((workObject.GroupFrequencyMax - workObject.GroupFrequencyMin) > 0) - attempts = workObject.GroupFrequencyMin + rand.nextInt(workObject.GroupFrequencyMax - workObject.GroupFrequencyMin); - - while (attempts > 0) - { - attempts--; - - int objIndex = rand.nextInt(workObject.GroupObjects.length); - CustomObjectCompiled ObjectFromGroup = workObject.GroupObjects[objIndex]; - - if (ObjectFromGroup.Branch) - continue; - - x = x + rand.nextInt(workObject.GroupSeparationMax - workObject.GroupSeparationMin) + workObject.GroupSeparationMin; - z = z + rand.nextInt(workObject.GroupSeparationMax - workObject.GroupSeparationMin) + workObject.GroupSeparationMin; - int _y; - - if (workObject.SpawnAboveGround) - _y = world.getSolidHeight(x, z); - else if (workObject.SpawnUnderGround) - { - int solidHeight = world.getSolidHeight(x, z); - if (solidHeight < 1 || solidHeight <= workObject.SpawnElevationMin) - continue; - if (solidHeight > workObject.SpawnElevationMax) - solidHeight = workObject.SpawnElevationMax; - _y = rand.nextInt(solidHeight - workObject.SpawnElevationMin) + workObject.SpawnElevationMin; - } else - _y = world.getHighestBlockYAt(x, z); - - if (y < 0) - continue; - - if ((y - _y) > 10 || (_y - y) > 10) - continue; - - if (!ObjectCanSpawn(world, x, y, z, ObjectFromGroup)) - continue; - GenerateCustomObject(world, rand, x, _y, z, ObjectFromGroup); - } - - - } - - - public static boolean GenerateCustomObject(LocalWorld world, Random rand, int x, int y, int z, CustomObjectCompiled workObject) - { - - ObjectCoordinate[] data = workObject.Data[0]; - if (workObject.RandomRotation) - data = workObject.Data[rand.nextInt(4)]; - - - int faultCounter = 0; - - for (ObjectCoordinate point : data) - { - if (!world.isLoaded((x + point.x), (y + point.y), (z + point.z))) - return false; - - if (!workObject.Dig) - { - if (workObject.CollisionBlockType.contains(world.getTypeId((x + point.x), (y + point.y), (z + point.z)))) - { - faultCounter++; - if (faultCounter > (data.length * (workObject.CollisionPercentage / 100))) - { - return false; - } - } - } - - - } - - for (ObjectCoordinate point : data) - { - - if (world.getTypeId(x + point.x, y + point.y, z + point.z) == 0) - { - world.setBlock((x + point.x), y + point.y, z + point.z, point.BlockId, point.BlockData, true, false, true); - } else if (workObject.Dig) - { - world.setBlock((x + point.x), y + point.y, z + point.z, point.BlockId, point.BlockData, true, false, true); - } - - } - return true; - - } - - public static boolean ObjectCanSpawn(LocalWorld world, int x, int y, int z, CustomObjectCompiled obj) - { - if ((world.getTypeId(x, y - 5, z) == 0) && (obj.NeedsFoundation)) - return false; - - boolean output = true; - int checkBlock = world.getTypeId(x, y + 2, z); - if (!obj.SpawnWater) - output = !((checkBlock == DefaultMaterial.WATER.id) || (checkBlock == DefaultMaterial.STATIONARY_WATER.id)); - if (!obj.SpawnLava) - output = !((checkBlock == DefaultMaterial.LAVA.id) || (checkBlock == DefaultMaterial.STATIONARY_LAVA.id)); - - checkBlock = world.getLightLevel(x, y + 2, z); - if (!obj.SpawnSunlight) - output = !(checkBlock > 8); - if (!obj.SpawnDarkness) - output = !(checkBlock < 9); - - if ((y < obj.SpawnElevationMin) || (y > obj.SpawnElevationMax)) - output = false; - - if (!obj.SpawnOnBlockType.contains(world.getTypeId(x, y - 1, z))) - output = false; - - return output; - } - - @Override - protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, int z) - { - - - } - - @Override - protected String WriteString(Resource res, String blockSources) - { - String output = """"; - boolean first = true; - - for (String name : res.CUObjectsNames) - { - output = output + (first ? """" : "",""); - if (first) - first = false; - - if (name.equals(BODefaultValues.BO_Use_World.stringValue()) || name.equals(BODefaultValues.BO_Use_Biome.stringValue())) - { - output += name; - continue; - } - - for (CustomObjectCompiled object : res.CUObjects) - if (object.Name.equals(name)) - output += name + (object.ChangedSettings.equals("""") ? """" : (""("" + object.ChangedSettings + "")"")); - - } - - return output; - - } - - @Override - protected boolean ReadString(Resource res, String[] Props, BiomeConfig biomeConfig) throws NumberFormatException - { - - ArrayList objects = new ArrayList(); - ArrayList objectsName = new ArrayList(); - HashMap> Groups = new HashMap>(); - - if (Props.length == 1 && Props[0].equals("""")) - { - AddCompiledObjectsFromWorld(biomeConfig, objects, Groups); - objectsName.add(BODefaultValues.BO_Use_World.stringValue()); - - } else - for (String key : Props) - { - if (key.equals(BODefaultValues.BO_Use_World.stringValue())) - { - AddCompiledObjectsFromWorld(biomeConfig, objects, Groups); - objectsName.add(BODefaultValues.BO_Use_World.stringValue()); - continue; - } - - if (key.equals(BODefaultValues.BO_Use_Biome.stringValue())) - { - AddCompiledObjectsFromBiome(biomeConfig, objects, Groups); - objectsName.add(BODefaultValues.BO_Use_Biome.stringValue()); - continue; - } - - CustomObjectCompiled obj = ObjectsStore.CompileString(key, biomeConfig.worldConfig.CustomObjectsDirectory); - if (obj == null) - obj = ObjectsStore.CompileString(key, ObjectsStore.GlobalDirectory); - if (obj != null) - { - objects.add(obj); - objectsName.add(obj.Name); - - if (!obj.GroupId.equals("""")) - { - if (!Groups.containsKey(obj.GroupId)) - Groups.put(obj.GroupId, new ArrayList()); - - Groups.get(obj.GroupId).add(obj); - - } - - - } - - } - - for (CustomObjectCompiled objectCompiled : objects) - { - if (Groups.containsKey(objectCompiled.GroupId)) - { - objectCompiled.GroupObjects = Groups.get(objectCompiled.GroupId).toArray(new CustomObjectCompiled[0]); - } - } - - res.CUObjects = objects.toArray(res.CUObjects); - res.CUObjectsNames = objectsName.toArray(res.CUObjectsNames); - - return true; - } - - - private void AddCompiledObjectsFromWorld(BiomeConfig biomeConfig, ArrayList output, HashMap> groups) - { - for (CustomObjectCompiled objectCompiled : biomeConfig.worldConfig.CustomObjectsCompiled) - if (objectCompiled.CheckBiome(biomeConfig.Name)) - { - output.add(objectCompiled); - if (!objectCompiled.GroupId.equals("""")) - { - if (!groups.containsKey(objectCompiled.GroupId)) - groups.put(objectCompiled.GroupId, new ArrayList()); - - groups.get(objectCompiled.GroupId).add(objectCompiled); - - } - - } - - } - - private void AddCompiledObjectsFromBiome(BiomeConfig biomeConfig, ArrayList output, HashMap> groups) - { - for (CustomObjectCompiled objectCompiled : biomeConfig.CustomObjectsCompiled) - { - output.add(objectCompiled); - if (!objectCompiled.GroupId.equals("""")) - { - if (!groups.containsKey(objectCompiled.GroupId)) - groups.put(objectCompiled.GroupId, new ArrayList()); - - groups.get(objectCompiled.GroupId).add(objectCompiled); - - } - - } - - } - -} diff --git a/common/src/com/khorn/terraincontrol/customobjects/CustomObjectLoader.java b/common/src/com/khorn/terraincontrol/customobjects/CustomObjectLoader.java new file mode 100644 index 000000000..b4ab6a652 --- /dev/null +++ b/common/src/com/khorn/terraincontrol/customobjects/CustomObjectLoader.java @@ -0,0 +1,8 @@ +package com.khorn.terraincontrol.customobjects; + +import java.io.File; + +public interface CustomObjectLoader +{ + public CustomObject loadFromFile(String objectName, File file); +} diff --git a/common/src/com/khorn/terraincontrol/customobjects/CustomObjectManager.java b/common/src/com/khorn/terraincontrol/customobjects/CustomObjectManager.java new file mode 100644 index 000000000..580a41005 --- /dev/null +++ b/common/src/com/khorn/terraincontrol/customobjects/CustomObjectManager.java @@ -0,0 +1,221 @@ +package com.khorn.terraincontrol.customobjects; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import com.khorn.terraincontrol.LocalWorld; +import com.khorn.terraincontrol.TerrainControl; +import com.khorn.terraincontrol.configuration.WorldConfig; +import com.khorn.terraincontrol.customobjects.bo2.BO2Loader; +import com.khorn.terraincontrol.generator.resourcegens.TreeType; + +public class CustomObjectManager +{ + /* + * Khoorn's comment, copied from the removed class ObjectsStore: + + Load: + 1)Load here all objects. + 2)Start save coordinates thread. + 2)Pre compile objects (make arrays for different angle) ?? + 3)Compile custom objects array for each biome. Based on world Bo2 list + Biome Bo2 list + Biome CustomTree list + a) store in one array in biome + b) store in different arrays in biome ??? + 4) Load ObjectCoordinates from file and add that instance to save thread. + + New load + 1) Load all objects from world directory + 2) Search and load objects from plugin directory + + + + Spawn: + 1)CustomObject resource, Tree resource, sapling, command + 2)Select random object if needed. + 3)Check for biome and select CustomBiome array if needed. + 4)Check for spawn conditions. + 5)Check for collision + a) Check for block collisions + b) If out of loaded chunks and object.dig == false - drop. + c) If out of loaded chunks and object.branch && !object.digBranch == true - drop + d) ?? + 6)Set blocks + a) If out of loaded chunks - get ObjectBuffer from CoordinatesStore and save to it. + b) If found branch start point - select random branch from group and call 5 for it. + + + Calculate branch size for in chunk check?? + Call branch in this chunk or in next ?? + + */ + + + + public final Map loaders; + public final Map globalObjects; + + public CustomObjectManager(Map loaders, Map globalObjects) + { + // These are the actual lists, not just a copy. + this.loaders = loaders; + this.globalObjects = globalObjects; + + // Register loaders + TerrainControl.registerCustomObjectLoader(""bo2"", new BO2Loader()); + + // Load all global objects (they can overwrite special objects) + TerrainControl.getEngine().getGlobalObjectsDirectory().mkdirs(); + this.globalObjects.putAll(loadObjects(TerrainControl.getEngine().getGlobalObjectsDirectory())); + TerrainControl.log(this.globalObjects.size() + "" global custom objects loaded.""); + + // Put some default CustomObjects + for(TreeType type: TreeType.values()) + { + globalObjects.put(type.name().toLowerCase(), new TreeObject(type)); + } + globalObjects.put(""useworld"", new UseWorld()); + globalObjects.put(""usebiome"", new UseBiome()); + } + + /** + * Returns the global CustomObject with the given name. + * @param name Name of the CustomObject, case-insensitive. + * @return The CustomObject, or null if there isn't one with that name. + */ + public CustomObject getCustomObject(String name) + { + return globalObjects.get(name.toLowerCase()); + } + + /** + * Returns the CustomObject with the given name. It searches for a world object first, and then it searches for a global object. + * @param name Name of the CustomObject, case-insensitive. + * @param world The world to search in first before searching the global objects. + * @return The CustomObject, or null if there isn't one with that name. + */ + public CustomObject getCustomObject(String name, LocalWorld world) + { + return getCustomObject(name, world.getSettings()); + } + + /** + * Returns the CustomObject with the given name. It searches for a world object first, and then it searches for a global object. + * @param name Name of the CustomObject, case-insensitive. + * @param config The config to search in first before searching the global objects. + * @return The CustomObject, or null if there isn't one with that name. + */ + public CustomObject getCustomObject(String name, WorldConfig config) + { + if(config.customObjects.containsKey(name.toLowerCase())) { + return config.customObjects.get(name.toLowerCase()); + } + return getCustomObject(name); + } + + /** + * Returns a Map with all CustomObjects in a directory in it. The Map will + * have the lowercase object name as a key. + * + * @param directory + * The directory to load from. + * @return + */ + public Map loadObjects(File directory) + { + if (!directory.isDirectory()) + { + throw new IllegalArgumentException(""Given file is not a directory: "" + directory.getAbsolutePath()); + } + + Map objects = new HashMap(); + for (File file : directory.listFiles()) + { + // Get name and extension + String[] fileName = file.getName().split(""\\.""); + String objectName; + String objectType; + if (fileName.length == 1) + { + // Found an object without an extension + objectName = fileName[0]; + objectType = """"; + } else + { + // Found an object with an extension + objectType = fileName[fileName.length - 1]; + objectName = """"; + for (int i = 0; i < fileName.length - 2; i++) + { + objectName += fileName[i]; + } + } + + // Get the object + CustomObjectLoader loader = loaders.get(objectType); + if (loader != null) + { + objects.put(objectName.toLowerCase(), loader.loadFromFile(objectName, file)); + } + } + + return objects; + } + + /** + * Parses a String in the format name(setting1=foo,setting2=bar) and returns a CustomObject. + * @param string + * @param world The world to search in + * @return A CustomObject, or null if no one was found. + */ + public CustomObject getObjectFromString(String string, LocalWorld world) + { + return this.getObjectFromString(string, world.getSettings()); + } + + /** + * Parses a String in the format name(setting1=foo,setting2=bar) and returns a CustomObject. + * @param string + * @param config The config to search in + * @return A CustomObject, or null if no one was found. + */ + public CustomObject getObjectFromString(String string, WorldConfig config) + { + String[] parts = new String[]{string, """"}; + + int start = string.indexOf(""(""); + int end = string.lastIndexOf("")""); + if (start != -1 && end != -1) + { + parts[0] = string.substring(0, start); + parts[1] = string.substring(start + 1, end); + } + + CustomObject object = getCustomObject(parts[0], config); + + if(object != null && parts[1].length() != 0) { + // More settings have been given + Map settingsMap = new HashMap(); + + String[] settings = parts[1].split("";""); + for(String setting: settings) + { + String[] settingParts = setting.split(""=""); + if(settingParts.length == 1) + { + // Boolean values + settingsMap.put(settingParts[0], ""true""); + } else if(settingParts.length == 2) + { + settingsMap.put(settingParts[0], settingParts[1]); + } + } + + if(settingsMap.size() > 0) + { + object = object.applySettings(settingsMap); + } + } + + return object; + } +} diff --git a/common/src/com/khorn/terraincontrol/customobjects/ObjectBuffer.java b/common/src/com/khorn/terraincontrol/customobjects/ObjectBuffer.java deleted file mode 100644 index fb4562ae5..000000000 --- a/common/src/com/khorn/terraincontrol/customobjects/ObjectBuffer.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.khorn.terraincontrol.customobjects; - -public class ObjectBuffer -{ - -} diff --git a/common/src/com/khorn/terraincontrol/customobjects/ObjectCoordinatesStore.java b/common/src/com/khorn/terraincontrol/customobjects/ObjectCoordinatesStore.java deleted file mode 100644 index 1236b4b6d..000000000 --- a/common/src/com/khorn/terraincontrol/customobjects/ObjectCoordinatesStore.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.khorn.terraincontrol.customobjects; - -import java.io.File; -import java.util.Hashtable; - -public class ObjectCoordinatesStore implements Runnable -{ - - public Hashtable Coordinates; - - public ObjectCoordinatesStore() - { - this.Coordinates = new Hashtable(); - - } - - public void ReadStore(File data) - { - - } - - // Save thread. - @Override - public void run() - { - - } -} diff --git a/common/src/com/khorn/terraincontrol/customobjects/ObjectsStore.java b/common/src/com/khorn/terraincontrol/customobjects/ObjectsStore.java deleted file mode 100644 index b54a7a491..000000000 --- a/common/src/com/khorn/terraincontrol/customobjects/ObjectsStore.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.khorn.terraincontrol.customobjects; - - -import java.io.File; -import java.util.ArrayList; - -public class ObjectsStore -{ - - /* - Load: - 1)Load here all objects. - 2)Start save coordinates thread. - 2)Pre compile objects (make arrays for different angle) ?? - 3)Compile custom objects array for each biome. Based on world Bo2 list + Biome Bo2 list + Biome CustomTree list - a) store in one array in biome - b) store in different arrays in biome ??? - 4) Load ObjectCoordinates from file and add that instance to save thread. - - New load - 1) Load all objects from world directory - 2) Search and load objects from plugin directory - - - - Spawn: - 1)CustomObject resource, Tree resource, sapling, command - 2)Select random object if needed. - 3)Check for biome and select CustomBiome array if needed. - 4)Check for spawn conditions. - 5)Check for collision - a) Check for block collisions - b) If out of loaded chunks and object.dig == false - drop. - c) If out of loaded chunks and object.branch && !object.digBranch == true - drop - d) ?? - 6)Set blocks - a) If out of loaded chunks - get ObjectBuffer from CoordinatesStore and save to it. - b) If found branch start point - select random branch from group and call 5 for it. - - - Calculate branch size for in chunk check?? - Call branch in this chunk or in next ?? - - - - - - */ - - - public static File GlobalDirectory; - - public static void ReadObjects(File pluginPath) - { - GlobalDirectory = new File(pluginPath, BODefaultValues.BO_GlobalDirectoryName.stringValue()); - - if (!GlobalDirectory.exists()) - { - if (!GlobalDirectory.mkdirs()) - { - System.out.println(""TerrainControl: can`t create GlobalObjects directory""); - } - } - - - //objectsList = LoadObjectsFromDirectory(directory); - - //System.out.println(""TerrainControl: "" + objectsList.size() + "" custom objects loaded""); - - - } - - - public static ArrayList LoadObjectsFromDirectory(File path) - { - ArrayList outputList = new ArrayList(); - - File[] files = path.listFiles(); - if (files == null) - return outputList; - - for (File customObjectFile : files) - { - if (customObjectFile.isFile()) - { - CustomObject object = new CustomObject(customObjectFile); - if (object.IsValid) - outputList.add(object); - } - } - return outputList; - - - } - - public static String[] ParseString(String key) - { - String[] output = new String[]{key, """"}; - - int start = key.indexOf(""(""); - int end = key.lastIndexOf("")""); - if (start != -1 && end != -1) - { - output[0] = key.substring(0, start); - output[1] = key.substring(start + 1, end); - } - return output; - } - - public static CustomObject GetObjectFromDirectory(String name, File directory) - { - File customObjectFile = new File(directory, name+"".""+BODefaultValues.BO_Extension.stringValue()); - - if (!customObjectFile.isFile()) - { - return null; - } - - CustomObject object = new CustomObject(customObjectFile); - - if (!object.IsValid) - { - return null; - } - - return object; - } - - public static CustomObjectCompiled CompileString(String key, File directory) - { - String[] values = ParseString(key); - CustomObject object = GetObjectFromDirectory(values[0], directory); - - if (object == null) - return null; - - return object.Compile(values[1]); - } -} diff --git a/common/src/com/khorn/terraincontrol/customobjects/TreeObject.java b/common/src/com/khorn/terraincontrol/customobjects/TreeObject.java new file mode 100644 index 000000000..aa19e3a59 --- /dev/null +++ b/common/src/com/khorn/terraincontrol/customobjects/TreeObject.java @@ -0,0 +1,90 @@ +package com.khorn.terraincontrol.customobjects; + +import java.util.Map; +import java.util.Random; + +import com.khorn.terraincontrol.LocalBiome; +import com.khorn.terraincontrol.LocalWorld; +import com.khorn.terraincontrol.generator.resourcegens.TreeType; + +public class TreeObject implements CustomObject +{ + TreeType type; + + public TreeObject(TreeType type) + { + this.type = type; + } + + @Override + public String getName() + { + return type.name(); + } + + @Override + public boolean canSpawnAsTree() + { + return true; + } + + @Override + public boolean canSpawnAsObject() + { + return false; + } + + @Override + public boolean spawn(LocalWorld world, Random random, int x, int y, int z) + { + return world.PlaceTree(type, random, x, y, z); + } + + @Override + public boolean spawnAsTree(LocalWorld world, Random random, int x, int y, int z) + { + return world.PlaceTree(type, random, x, y, z); + } + + @Override + public boolean spawn(LocalWorld world, Random random, int x, int z) + { + return world.PlaceTree(type, random, x, world.getHighestBlockYAt(x, z), z); + } + + @Override + public boolean spawnAsTree(LocalWorld world, Random random, int x, int z) + { + return world.PlaceTree(type, random, x, world.getHighestBlockYAt(x, z), z); + } + + @Override + public void process(LocalWorld world, Random random, int chunkX, int chunkZ) + { + // A tree has no rarity, so spawn it once in the chunk + int x = chunkX * 16 + random.nextInt(16); + int z = chunkZ * 16 + random.nextInt(16); + int y = world.getHighestBlockYAt(x, z); + world.PlaceTree(type, random, x, y, z); + } + + @Override + public void processAsTree(LocalWorld world, Random random, int chunkX, int chunkZ) + { + process(world, random, chunkX, chunkZ); + } + + @Override + public CustomObject applySettings(Map settings) + { + // Trees don't support this + return this; + } + + @Override + public boolean hasPreferenceToSpawnIn(LocalBiome biome) + { + return true; + } + +} diff --git a/common/src/com/khorn/terraincontrol/customobjects/UseBiome.java b/common/src/com/khorn/terraincontrol/customobjects/UseBiome.java new file mode 100644 index 000000000..ca6864099 --- /dev/null +++ b/common/src/com/khorn/terraincontrol/customobjects/UseBiome.java @@ -0,0 +1,124 @@ +package com.khorn.terraincontrol.customobjects; + +import java.util.ArrayList; +import java.util.Map; +import java.util.Random; + +import com.khorn.terraincontrol.LocalBiome; +import com.khorn.terraincontrol.LocalWorld; + +/** + * UseBiome is a keyword that spawns the objects in the BiomeConfig/BiomeObjects + * setting. + * + */ +public class UseBiome implements CustomObject +{ + public ArrayList getPossibleObjectsAt(LocalWorld world, int x, int z) + { + return world.getSettings().biomeConfigs[world.getBiome(x, z).getId()].biomeObjects; + } + + @Override + public String getName() + { + return ""UseBiome""; + } + + @Override + public boolean canSpawnAsTree() + { + return true; + } + + @Override + public boolean canSpawnAsObject() + { + return true; + } + + @Override + public boolean spawn(LocalWorld world, Random random, int x, int y, int z) + { + for (CustomObject object : getPossibleObjectsAt(world, x, z)) + { + if (object.spawn(world, random, x, y, z)) + { + return true; + } + } + return false; + } + + @Override + public boolean spawnAsTree(LocalWorld world, Random random, int x, int y, int z) + { + for (CustomObject object : getPossibleObjectsAt(world, x, z)) + { + if (object.spawnAsTree(world, random, x, y, z)) + { + return true; + } + } + return false; + } + + @Override + public boolean spawn(LocalWorld world, Random random, int x, int z) + { + for (CustomObject object : getPossibleObjectsAt(world, x, z)) + { + if (object.spawn(world, random, x, z)) + { + return true; + } + } + return false; + } + + @Override + public boolean spawnAsTree(LocalWorld world, Random random, int x, int z) + { + for (CustomObject object : getPossibleObjectsAt(world, x, z)) + { + if (object.spawnAsTree(world, random, x, z)) + { + return true; + } + } + return false; + } + + @Override + public void process(LocalWorld world, Random random, int chunkX, int chunkZ) + { + for (CustomObject object : getPossibleObjectsAt(world, chunkX * 16 + 8, chunkZ * 16 + 8)) + { + object.process(world, random, chunkX, chunkZ); + } + } + + @Override + public void processAsTree(LocalWorld world, Random random, int chunkX, int chunkZ) + { + for (CustomObject object : getPossibleObjectsAt(world, chunkX * 16 + 8, chunkZ * 16 + 8)) + { + object.processAsTree(world, random, chunkX, chunkZ); + } + } + + @Override + public CustomObject applySettings(Map settings) + { + // Not supported + return this; + } + + @Override + public boolean hasPreferenceToSpawnIn(LocalBiome biome) + { + // Never, ever spawn this with UseWorld. + return false; + } + +} diff --git a/common/src/com/khorn/terraincontrol/customobjects/UseWorld.java b/common/src/com/khorn/terraincontrol/customobjects/UseWorld.java new file mode 100644 index 000000000..cfd50f842 --- /dev/null +++ b/common/src/com/khorn/terraincontrol/customobjects/UseWorld.java @@ -0,0 +1,118 @@ +package com.khorn.terraincontrol.customobjects; + +import java.util.Map; +import java.util.Random; + +import com.khorn.terraincontrol.LocalBiome; +import com.khorn.terraincontrol.LocalWorld; + +/** + * UseWorld is a keyword that spawns the objects in the WorldObjects folder. + * + */ +public class UseWorld implements CustomObject +{ + + @Override + public String getName() + { + return ""UseWorld""; + } + + @Override + public boolean canSpawnAsTree() + { + return true; + } + + @Override + public boolean canSpawnAsObject() + { + return true; + } + + @Override + public boolean spawn(LocalWorld world, Random random, int x, int y, int z) + { + for(CustomObject object: world.getSettings().customObjects.values()) + { + if(object.hasPreferenceToSpawnIn(world.getBiome(x, z)) && object.spawn(world, random, x, y, z)) + { + return true; + } + } + return false; + } + + @Override + public boolean spawnAsTree(LocalWorld world, Random random, int x, int y, int z) + { + for(CustomObject object: world.getSettings().customObjects.values()) + { + if(object.spawnAsTree(world, random, x, y, z)) + { + return true; + } + } + return false; + } + + @Override + public boolean spawn(LocalWorld world, Random random, int x, int z) + { + for(CustomObject object: world.getSettings().customObjects.values()) + { + if(object.spawn(world, random, x, z)) + { + return true; + } + } + return false; + } + + @Override + public boolean spawnAsTree(LocalWorld world, Random random, int x, int z) + { + for(CustomObject object: world.getSettings().customObjects.values()) + { + if(object.spawnAsTree(world, random, x, z)) + { + return true; + } + } + return false; + } + + @Override + public void process(LocalWorld world, Random random, int chunkX, int chunkZ) + { + for(CustomObject object: world.getSettings().customObjects.values()) + { + object.process(world, random, chunkX, chunkZ); + } + } + + @Override + public void processAsTree(LocalWorld world, Random random, int chunkX, int chunkZ) + { + for(CustomObject object: world.getSettings().customObjects.values()) + { + object.processAsTree(world, random, chunkX, chunkZ); + } + } + + @Override + public CustomObject applySettings(Map settings) + { + // Not supported + return this; + } + + @Override + public boolean hasPreferenceToSpawnIn(LocalBiome biome) + { + // Never, ever spawn this in UseWorld. It would cause an infinite loop. + return false; + } + +} diff --git a/common/src/com/khorn/terraincontrol/customobjects/bo2/BO2.java b/common/src/com/khorn/terraincontrol/customobjects/bo2/BO2.java new file mode 100644 index 000000000..638fe02bf --- /dev/null +++ b/common/src/com/khorn/terraincontrol/customobjects/bo2/BO2.java @@ -0,0 +1,454 @@ +package com.khorn.terraincontrol.customobjects.bo2; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Random; + +import com.khorn.terraincontrol.DefaultMaterial; +import com.khorn.terraincontrol.LocalBiome; +import com.khorn.terraincontrol.LocalWorld; +import com.khorn.terraincontrol.configuration.ConfigFile; +import com.khorn.terraincontrol.customobjects.BODefaultValues; +import com.khorn.terraincontrol.customobjects.CustomObject; +import com.khorn.terraincontrol.customobjects.ObjectCoordinate; + +/** + * The good old BO2. + * + */ +public class BO2 extends ConfigFile implements CustomObject +{ + public ObjectCoordinate[][] Data = new ObjectCoordinate[4][]; + + public BO2[] GroupObjects = null; + + public String Name; + + public HashSet SpawnInBiome; + + public String Version; + public HashSet SpawnOnBlockType; + + public HashSet CollisionBlockType; + + public boolean SpawnWater; + public boolean SpawnLava; + public boolean SpawnAboveGround; + public boolean SpawnUnderGround; + + public boolean SpawnSunlight; + public boolean SpawnDarkness; + + public boolean UnderFill; + public boolean RandomRotation; + public boolean Dig; + public boolean Tree; + public boolean Branch; + public boolean DiggingBranch; + public boolean NeedsFoundation; + public int Rarity; + public double CollisionPercentage; + public int SpawnElevationMin; + public int SpawnElevationMax; + + public int GroupFrequencyMin; + public int GroupFrequencyMax; + public int GroupSeparationMin; + public int GroupSeparationMax; + public String GroupId; + + public int BranchLimit; + + public BO2(File file, String name) + { + ReadSettingsFile(file); + this.Name = name; + + ReadConfigSettings(); + CorrectSettings(); + } + + public BO2(Map settings, String name) + { + SettingsCache = settings; + this.Name = name; + + ReadConfigSettings(); + CorrectSettings(); + } + + @Override + public String getName() + { + return this.Name; + } + + @Override + public boolean canSpawnAsTree() + { + return Tree; + } + + @Override + public boolean canSpawnAsObject() + { + return true; + } + + @Override + public boolean spawn(LocalWorld world, Random random, int x, int y, int z) + { + if (!ObjectCanSpawn(world, x, y, z)) + { + return false; + } + + ObjectCoordinate[] data = Data[0]; + if (RandomRotation) + data = Data[random.nextInt(4)]; + + int faultCounter = 0; + + for (ObjectCoordinate point : data) + { + if (!world.isLoaded((x + point.x), (y + point.y), (z + point.z))) + return false; + + if (!Dig) + { + if (CollisionBlockType.contains(world.getTypeId((x + point.x), (y + point.y), (z + point.z)))) + { + faultCounter++; + if (faultCounter > (data.length * (CollisionPercentage / 100))) + { + return false; + } + } + } + + } + + for (ObjectCoordinate point : data) + { + + if (world.getTypeId(x + point.x, y + point.y, z + point.z) == 0) + { + world.setBlock((x + point.x), y + point.y, z + point.z, point.BlockId, point.BlockData, true, false, true); + } else if (Dig) + { + world.setBlock((x + point.x), y + point.y, z + point.z, point.BlockId, point.BlockData, true, false, true); + } + + } + return true; + } + + @Override + public boolean spawnAsTree(LocalWorld world, Random random, int x, int y, int z) + { + if (!Tree) + { + // Can only spawn as a tree if this is a tree. + return false; + } + return spawn(world, random, x, y, z); + } + + @Override + public boolean spawn(LocalWorld world, Random random, int x, int z) + { + int y; + if (SpawnAboveGround) + y = world.getSolidHeight(x, z); + else if (SpawnUnderGround) + { + int solidHeight = world.getSolidHeight(x, z); + if (solidHeight < 1 || solidHeight <= SpawnElevationMin) + return false; + if (solidHeight > SpawnElevationMax) + solidHeight = SpawnElevationMax; + y = random.nextInt(solidHeight - SpawnElevationMin) + SpawnElevationMin; + } else + y = world.getHighestBlockYAt(x, z); + + if (y < 0) + return false; + + if (!ObjectCanSpawn(world, x, y, z)) + return false; + + boolean objectSpawned = this.spawn(world, random, x, y, z); + + if (objectSpawned) + GenerateCustomObjectFromGroup(world, random, x, y, z); + + return objectSpawned; + } + + @Override + public boolean spawnAsTree(LocalWorld world, Random random, int x, int z) + { + return spawn(world, random, x, z); + } + + @Override + public void process(LocalWorld world, Random random, int chunkX, int chunkZ) + { + int randomRoll = random.nextInt(100); + int ObjectRarity = Rarity; + + while (randomRoll < ObjectRarity) + { + ObjectRarity -= 100; + + int x = chunkX * 16 + random.nextInt(16); + int z = chunkZ * 16 + random.nextInt(16); + + spawn(world, random, x, z); + } + } + + @Override + public void processAsTree(LocalWorld world, Random random, int chunkX, int chunkZ) + { + if (!Tree) + { + return; + } + + process(world, random, chunkX, chunkZ); + } + + @Override + public CustomObject applySettings(Map extraSettings) + { + Map newSettings = new HashMap(); + newSettings.putAll(SettingsCache); + newSettings.putAll(extraSettings); + return new BO2(newSettings, getName()); + } + + @Override + protected void WriteConfigSettings() throws IOException + { + // It doesn't write. + } + + @Override + protected void ReadConfigSettings() + { + this.Version = ReadModSettings(BODefaultValues.version.name(), BODefaultValues.version.stringValue()); + + this.SpawnOnBlockType = this.ReadBlockList(ReadModSettings(BODefaultValues.spawnOnBlockType.name(), BODefaultValues.spawnOnBlockType.StringArrayListValue()), BODefaultValues.spawnOnBlockType.name()); + this.CollisionBlockType = this.ReadBlockList(ReadModSettings(BODefaultValues.collisionBlockType.name(), BODefaultValues.collisionBlockType.StringArrayListValue()), BODefaultValues.collisionBlockType.name()); + + this.SpawnInBiome = new HashSet(ReadModSettings(BODefaultValues.spawnInBiome.name(), BODefaultValues.spawnInBiome.StringArrayListValue())); + + this.SpawnSunlight = ReadModSettings(BODefaultValues.spawnSunlight.name(), BODefaultValues.spawnSunlight.booleanValue()); + this.SpawnDarkness = ReadModSettings(BODefaultValues.spawnDarkness.name(), BODefaultValues.spawnDarkness.booleanValue()); + this.SpawnWater = ReadModSettings(BODefaultValues.spawnWater.name(), BODefaultValues.spawnWater.booleanValue()); + this.SpawnLava = ReadModSettings(BODefaultValues.spawnLava.name(), BODefaultValues.spawnLava.booleanValue()); + this.SpawnAboveGround = ReadModSettings(BODefaultValues.spawnAboveGround.name(), BODefaultValues.spawnAboveGround.booleanValue()); + this.SpawnUnderGround = ReadModSettings(BODefaultValues.spawnUnderGround.name(), BODefaultValues.spawnUnderGround.booleanValue()); + + this.UnderFill = ReadModSettings(BODefaultValues.underFill.name(), BODefaultValues.underFill.booleanValue()); + + this.RandomRotation = ReadModSettings(BODefaultValues.randomRotation.name(), BODefaultValues.randomRotation.booleanValue()); + this.Dig = ReadModSettings(BODefaultValues.dig.name(), BODefaultValues.dig.booleanValue()); + this.Tree = ReadModSettings(BODefaultValues.tree.name(), BODefaultValues.tree.booleanValue()); + this.Branch = ReadModSettings(BODefaultValues.branch.name(), BODefaultValues.branch.booleanValue()); + this.DiggingBranch = ReadModSettings(BODefaultValues.diggingBranch.name(), BODefaultValues.diggingBranch.booleanValue()); + this.NeedsFoundation = ReadModSettings(BODefaultValues.needsFoundation.name(), BODefaultValues.needsFoundation.booleanValue()); + this.Rarity = ReadModSettings(BODefaultValues.rarity.name(), BODefaultValues.rarity.intValue()); + this.CollisionPercentage = ReadModSettings(BODefaultValues.collisionPercentage.name(), BODefaultValues.collisionPercentage.intValue()); + this.SpawnElevationMin = ReadModSettings(BODefaultValues.spawnElevationMin.name(), BODefaultValues.spawnElevationMin.intValue()); + this.SpawnElevationMax = ReadModSettings(BODefaultValues.spawnElevationMax.name(), BODefaultValues.spawnElevationMax.intValue()); + + this.GroupFrequencyMin = ReadModSettings(BODefaultValues.groupFrequencyMin.name(), BODefaultValues.groupFrequencyMin.intValue()); + this.GroupFrequencyMax = ReadModSettings(BODefaultValues.groupFrequencyMax.name(), BODefaultValues.groupFrequencyMax.intValue()); + this.GroupSeparationMin = ReadModSettings(BODefaultValues.groupSeperationMin.name(), BODefaultValues.groupSeperationMin.intValue()); + this.GroupSeparationMax = ReadModSettings(BODefaultValues.groupSeperationMax.name(), BODefaultValues.groupSeperationMax.intValue()); + this.GroupId = ReadModSettings(BODefaultValues.groupId.name(), BODefaultValues.groupId.stringValue()); + + this.BranchLimit = ReadModSettings(BODefaultValues.branchLimit.name(), BODefaultValues.branchLimit.intValue()); + + this.ReadCoordinates(); + } + + @Override + protected void CorrectSettings() + { + // Stub method + } + + @Override + protected void RenameOldSettings() + { + // Stub method + } + + private void ReadCoordinates() + { + ArrayList coordinates = new ArrayList(); + + for (String key : SettingsCache.keySet()) + { + ObjectCoordinate buffer = ObjectCoordinate.getCoordinateFromString(key, SettingsCache.get(key)); + if (buffer != null) + coordinates.add(buffer); + } + + Data[0] = new ObjectCoordinate[coordinates.size()]; + Data[1] = new ObjectCoordinate[coordinates.size()]; + Data[2] = new ObjectCoordinate[coordinates.size()]; + Data[3] = new ObjectCoordinate[coordinates.size()]; + + for (int i = 0; i < coordinates.size(); i++) + { + ObjectCoordinate coordinate = coordinates.get(i); + + Data[0][i] = coordinate; + coordinate = coordinate.Rotate(); + Data[1][i] = coordinate; + coordinate = coordinate.Rotate(); + Data[2][i] = coordinate; + coordinate = coordinate.Rotate(); + Data[3][i] = coordinate; + } + + } + + private HashSet ReadBlockList(ArrayList blocks, String settingName) + { + HashSet output = new HashSet(); + + boolean nonIntegerValues = false; + boolean all = false; + boolean solid = false; + + for (String block : blocks) + { + + if (block.equals(BODefaultValues.BO_ALL_KEY.stringValue())) + { + all = true; + continue; + } + if (block.equals(BODefaultValues.BO_SolidKey.stringValue())) + { + solid = true; + continue; + } + try + { + int blockID = Integer.decode(block); + if (blockID != 0) + output.add(blockID); + } catch (NumberFormatException e) + { + nonIntegerValues = true; + } + } + + if (all || solid) + for (DefaultMaterial material : DefaultMaterial.values()) + { + if (material.id == 0) + continue; + if (solid && !material.isSolid()) + continue; + output.add(material.id); + + } + if (nonIntegerValues) + System.out.println(""TerrainControl: Custom object "" + this.Name + "" have wrong value "" + settingName); + + return output; + + } + + public boolean ObjectCanSpawn(LocalWorld world, int x, int y, int z) + { + if ((world.getTypeId(x, y - 5, z) == 0) && (NeedsFoundation)) + return false; + + boolean output = true; + int checkBlock = world.getTypeId(x, y + 2, z); + if (!SpawnWater) + output = !((checkBlock == DefaultMaterial.WATER.id) || (checkBlock == DefaultMaterial.STATIONARY_WATER.id)); + if (!SpawnLava) + output = !((checkBlock == DefaultMaterial.LAVA.id) || (checkBlock == DefaultMaterial.STATIONARY_LAVA.id)); + + checkBlock = world.getLightLevel(x, y + 2, z); + if (!SpawnSunlight) + output = !(checkBlock > 8); + if (!SpawnDarkness) + output = !(checkBlock < 9); + + if ((y < SpawnElevationMin) || (y > SpawnElevationMax)) + output = false; + + if (!SpawnOnBlockType.contains(world.getTypeId(x, y - 1, z))) + output = false; + + return output; + } + + public void GenerateCustomObjectFromGroup(LocalWorld world, Random random, int x, int y, int z) + { + if (GroupObjects == null) + return; + + int attempts = 3; + if ((GroupFrequencyMax - GroupFrequencyMin) > 0) + attempts = GroupFrequencyMin + random.nextInt(GroupFrequencyMax - GroupFrequencyMin); + + while (attempts > 0) + { + attempts--; + + int objIndex = random.nextInt(GroupObjects.length); + BO2 ObjectFromGroup = GroupObjects[objIndex]; + + if (Branch) + continue; + + x = x + random.nextInt(GroupSeparationMax - GroupSeparationMin) + GroupSeparationMin; + z = z + random.nextInt(GroupSeparationMax - GroupSeparationMin) + GroupSeparationMin; + int _y; + + if (SpawnAboveGround) + _y = world.getSolidHeight(x, z); + else if (SpawnUnderGround) + { + int solidHeight = world.getSolidHeight(x, z); + if (solidHeight < 1 || solidHeight <= SpawnElevationMin) + continue; + if (solidHeight > SpawnElevationMax) + solidHeight = SpawnElevationMax; + _y = random.nextInt(solidHeight - SpawnElevationMin) + SpawnElevationMin; + } else + _y = world.getHighestBlockYAt(x, z); + + if (y < 0) + continue; + + if ((y - _y) > 10 || (_y - y) > 10) + continue; + + ObjectFromGroup.spawn(world, random, x, _y, z); + } + + } + + @Override + public boolean hasPreferenceToSpawnIn(LocalBiome biome) + { + return SpawnInBiome.contains(biome.getName()) || SpawnInBiome.contains(""All""); + } + +} diff --git a/common/src/com/khorn/terraincontrol/customobjects/bo2/BO2Loader.java b/common/src/com/khorn/terraincontrol/customobjects/bo2/BO2Loader.java new file mode 100644 index 000000000..e7ee8bb76 --- /dev/null +++ b/common/src/com/khorn/terraincontrol/customobjects/bo2/BO2Loader.java @@ -0,0 +1,14 @@ +package com.khorn.terraincontrol.customobjects.bo2; + +import java.io.File; + +import com.khorn.terraincontrol.customobjects.CustomObject; +import com.khorn.terraincontrol.customobjects.CustomObjectLoader; + +public class BO2Loader implements CustomObjectLoader +{ + public CustomObject loadFromFile(String objectName, File file) + { + return new BO2(file, objectName); + } +} diff --git a/common/src/com/khorn/terraincontrol/exception/InvalidResourceException.java b/common/src/com/khorn/terraincontrol/exception/InvalidResourceException.java new file mode 100644 index 000000000..f53a907ae --- /dev/null +++ b/common/src/com/khorn/terraincontrol/exception/InvalidResourceException.java @@ -0,0 +1,11 @@ +package com.khorn.terraincontrol.exception; + +public class InvalidResourceException extends Exception +{ + + public InvalidResourceException(String string) + { + super(string); + } + +} diff --git a/common/src/com/khorn/terraincontrol/generator/ObjectSpawner.java b/common/src/com/khorn/terraincontrol/generator/ObjectSpawner.java index a0f81f51b..d0dde206a 100644 --- a/common/src/com/khorn/terraincontrol/generator/ObjectSpawner.java +++ b/common/src/com/khorn/terraincontrol/generator/ObjectSpawner.java @@ -1,14 +1,14 @@ package com.khorn.terraincontrol.generator; +import java.util.Random; + import com.khorn.terraincontrol.DefaultMaterial; import com.khorn.terraincontrol.LocalWorld; import com.khorn.terraincontrol.configuration.BiomeConfig; import com.khorn.terraincontrol.configuration.Resource; import com.khorn.terraincontrol.configuration.TCDefaultValues; import com.khorn.terraincontrol.configuration.WorldConfig; -import com.khorn.terraincontrol.generator.resourcegens.ResourceType; - -import java.util.Random; +import com.khorn.terraincontrol.generator.resourcegens.SmallLakeGen; public class ObjectSpawner { @@ -42,10 +42,10 @@ public void populate(int chunkX, int chunkZ) for (int i = 0; i < localBiomeConfig.ResourceCount; i++) { Resource res = localBiomeConfig.ResourceSequence[i]; - if (res.Type == ResourceType.SmallLake && Village) + if (res instanceof SmallLakeGen && Village) continue; - world.setChunksCreations(res.Type.CreateNewChunks); - res.Type.Generator.Process(world, rand, res, x, z); + world.setChunksCreations(false); + res.process(world, rand, chunkX, chunkZ); } // Snow and ice @@ -67,10 +67,11 @@ public void populate(int chunkX, int chunkZ) world.setBlock(blockToFreezeX, blockToFreezeY - 1, blockToFreezeZ, biomeConfig.iceBlock, 0); } else { - // Snow has to be placed on an empty space on a solid block in the world + // Snow has to be placed on an empty space on a + // solid block in the world if (world.getMaterial(blockToFreezeX, blockToFreezeY, blockToFreezeZ) == DefaultMaterial.AIR) { - if (world.getMaterial(blockToFreezeX, blockToFreezeY - 1, blockToFreezeZ).isSolid()) + if (world.getMaterial(blockToFreezeX, blockToFreezeY - 1, blockToFreezeZ).isSolid()) { world.setBlock(blockToFreezeX, blockToFreezeY, blockToFreezeZ, DefaultMaterial.SNOW.id, 0); } diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/AboveWaterGen.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/AboveWaterGen.java index 63f205514..b4060afca 100644 --- a/common/src/com/khorn/terraincontrol/generator/resourcegens/AboveWaterGen.java +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/AboveWaterGen.java @@ -1,15 +1,33 @@ package com.khorn.terraincontrol.generator.resourcegens; import com.khorn.terraincontrol.LocalWorld; -import com.khorn.terraincontrol.configuration.BiomeConfig; import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.exception.InvalidResourceException; +import java.util.List; import java.util.Random; -public class AboveWaterGen extends ResourceGenBase +public class AboveWaterGen extends Resource { + private int blockId; + private int blockData; + @Override - protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, int z) + public void load(List args) throws InvalidResourceException + { + if (args.size() < 3) + { + throw new InvalidResourceException(""Too few arguments supplied""); + } + + blockId = getBlockId(args.get(0)); + blockData = getBlockData(args.get(0)); + frequency = getInt(args.get(1), 1, 100); + rarity = getInt(args.get(2), 1, 100); + } + + @Override + public void spawn(LocalWorld world, Random rand, int x, int z) { int y = world.getLiquidHeight(x, z); if (y == -1) @@ -19,26 +37,23 @@ protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, for (int i = 0; i < 10; i++) { int j = x + rand.nextInt(8) - rand.nextInt(8); - //int k = y + rand.nextInt(4) - rand.nextInt(4); int m = z + rand.nextInt(8) - rand.nextInt(8); if (!world.isEmpty(j, y, m) || !world.getMaterial(j, y - 1, m).isLiquid()) continue; - world.setBlock(j, y, m, res.BlockId, 0, false, false, false); + world.setBlock(j, y, m, blockId, blockData, false, false, false); } } @Override - protected boolean ReadString(Resource res, String[] Props, BiomeConfig biomeConfig) throws NumberFormatException + public ResourceType getType() { - res.BlockId = CheckBlock(Props[0]); - res.Frequency = CheckValue(Props[1], 1, 100); - res.Rarity = CheckValue(Props[2], 0, 100); - return true; + return ResourceType.biomeConfigResource; } @Override - protected String WriteString(Resource res, String blockSources) + public String makeString() { - return res.BlockIdToName(res.BlockId) + "","" + res.Frequency + "","" + res.Rarity; + return ""AboveWaterGen("" + makeMaterial(blockId) + "","" + frequency + "","" + rarity + "")""; } + } diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/CactusGen.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/CactusGen.java index 9e530c630..f0f1f2cfa 100644 --- a/common/src/com/khorn/terraincontrol/generator/resourcegens/CactusGen.java +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/CactusGen.java @@ -1,17 +1,26 @@ package com.khorn.terraincontrol.generator.resourcegens; -import com.khorn.terraincontrol.configuration.BiomeConfig; -import com.khorn.terraincontrol.configuration.Resource; -import com.khorn.terraincontrol.LocalWorld; - +import java.util.ArrayList; +import java.util.List; import java.util.Random; -public class CactusGen extends ResourceGenBase +import com.khorn.terraincontrol.LocalWorld; +import com.khorn.terraincontrol.TerrainControl; +import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.exception.InvalidResourceException; + +public class CactusGen extends Resource { + private int blockId; + private int blockData; + private int minAltitude; + private int maxAltitude; + private List sourceBlocks; + @Override - protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, int z) + public void spawn(LocalWorld world, Random rand, int x, int z) { - int y = rand.nextInt(res.MaxAltitude - res.MinAltitude) + res.MinAltitude; + int y = rand.nextInt(maxAltitude - minAltitude) + minAltitude; for (int i = 0; i < 10; i++) { @@ -24,9 +33,9 @@ protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, for (int i1 = 0; i1 < n; i1++) { int id = world.getTypeId(j, k + i1 - 1, m); - if (res.CheckSourceId(id) || id == res.BlockId) + if (sourceBlocks.contains(id)) { - world.setBlock(j, k + i1, m, res.BlockId, 0, false, false, false); + world.setBlock(j, k + i1, m, blockId, blockData, false, false, false); } } } @@ -34,39 +43,35 @@ protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, } @Override - protected boolean ReadString(Resource res, String[] Props, BiomeConfig biomeConfig) throws NumberFormatException + public ResourceType getType() { + return ResourceType.biomeConfigResource; + } - if (Props[0].contains(""."")) - { - String[] block = Props[0].split(""\\.""); - res.BlockId = CheckBlock(block[0]); - res.BlockData = CheckValue(block[1], 0, 16); - } else - { - res.BlockId = CheckBlock(Props[0]); - } - - res.Frequency = CheckValue(Props[1], 1, 100); - res.Rarity = CheckValue(Props[2], 0, 100); - res.MinAltitude = CheckValue(Props[3], 0, biomeConfig.worldConfig.WorldHeight); - res.MaxAltitude = CheckValue(Props[4], 0, biomeConfig.worldConfig.WorldHeight, res.MinAltitude); - - res.SourceBlockId = new int[Props.length - 5]; - for (int i = 5; i < Props.length; i++) - res.SourceBlockId[i - 5] = CheckBlock(Props[i]); - - return true; + @Override + public String makeString() + { + return ""Cactus("" + makeMaterial(blockId, blockData) + "","" + frequency + "","" + rarity + "","" + minAltitude + "","" + maxAltitude + makeMaterial(sourceBlocks); } @Override - protected String WriteString(Resource res, String blockSources) + public void load(List args) throws InvalidResourceException { - String blockId = res.BlockIdToName(res.BlockId); - if (res.BlockData > 0) + if (args.size() < 6) + { + throw new InvalidResourceException(""Too few arguments supplied""); + } + + blockId = getBlockId(args.get(0)); + blockData = getBlockData(args.get(0)); + frequency = getInt(args.get(1), 1, 100); + rarity = getInt(args.get(2), 1, 100); + minAltitude = getInt(args.get(3), TerrainControl.worldDepth, TerrainControl.worldHeight); + maxAltitude = getInt(args.get(4), minAltitude + 1, TerrainControl.worldHeight); + sourceBlocks = new ArrayList(); + for (int i = 5; i < args.size(); i++) { - blockId += ""."" + res.BlockData; + sourceBlocks.add(getBlockId(args.get(i))); } - return blockId + "","" + res.Frequency + "","" + res.Rarity + "","" + res.MinAltitude + "","" + res.MaxAltitude + blockSources; } } \ No newline at end of file diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/CustomObjectGen.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/CustomObjectGen.java new file mode 100644 index 000000000..a4a943e57 --- /dev/null +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/CustomObjectGen.java @@ -0,0 +1,67 @@ +package com.khorn.terraincontrol.generator.resourcegens; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import com.khorn.terraincontrol.LocalWorld; +import com.khorn.terraincontrol.TerrainControl; +import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.customobjects.CustomObject; +import com.khorn.terraincontrol.exception.InvalidResourceException; +import com.khorn.terraincontrol.util.Txt; + +public class CustomObjectGen extends Resource +{ + private List objects; + private List objectNames; + + @Override + public void load(List args) throws InvalidResourceException + { + if (args.size() == 0) + { + // Backwards compability + args.add(""UseWorld""); + } + objects = new ArrayList(); + for (String arg : args) + { + CustomObject object = TerrainControl.getCustomObjectManager().getObjectFromString(arg, worldConfig); + if (object == null || !object.canSpawnAsObject()) + { + throw new InvalidResourceException(""No custom object found with the name "" + arg); + } + objects.add(object); + objectNames.add(arg); + } + } + + @Override + public void spawn(LocalWorld world, Random random, int x, int z) + { + // Left blank, as process(..) already handles this. + } + + @Override + public void process(LocalWorld world, Random random, int chunkX, int chunkZ) + { + for (CustomObject object : objects) + { + object.process(world, random, chunkX, chunkZ); + } + } + + @Override + public ResourceType getType() + { + return ResourceType.biomeConfigResource; + } + + @Override + public String makeString() + { + return ""CustomObject("" + Txt.implode(objectNames, "","") + "")""; + } + +} diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/DungeonGen.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/DungeonGen.java index 630d447df..3d7b16d6a 100644 --- a/common/src/com/khorn/terraincontrol/generator/resourcegens/DungeonGen.java +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/DungeonGen.java @@ -1,34 +1,47 @@ package com.khorn.terraincontrol.generator.resourcegens; -import com.khorn.terraincontrol.configuration.BiomeConfig; import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.exception.InvalidResourceException; import com.khorn.terraincontrol.LocalWorld; +import com.khorn.terraincontrol.TerrainControl; +import java.util.List; import java.util.Random; -public class DungeonGen extends ResourceGenBase +public class DungeonGen extends Resource { + private int minAltitude; + private int maxAltitude; + @Override - protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, int z) + public void load(List args) throws InvalidResourceException { - int _y = rand.nextInt(res.MaxAltitude - res.MinAltitude) + res.MinAltitude; - world.PlaceDungeons(rand, x, _y, z); + if (args.size() < 4) + { + throw new InvalidResourceException(""Too few arguments supplied""); + } + frequency = getInt(args.get(0), 1, 100); + rarity = getInt(args.get(1), 1, 100); + minAltitude = getInt(args.get(2), TerrainControl.worldDepth, TerrainControl.worldHeight); + maxAltitude = getInt(args.get(3), minAltitude + 1, TerrainControl.worldHeight); } @Override - protected boolean ReadString(Resource res, String[] Props, BiomeConfig biomeConfig) throws NumberFormatException + public void spawn(LocalWorld world, Random random, int x, int z) { - res.Frequency = CheckValue(Props[0], 1, 100); - res.Rarity = CheckValue(Props[1], 0, 100); - res.MinAltitude = CheckValue(Props[2], 0, biomeConfig.worldConfig.WorldHeight); - res.MaxAltitude = CheckValue(Props[3], 0, biomeConfig.worldConfig.WorldHeight, res.MinAltitude); + int y = random.nextInt(maxAltitude - minAltitude) + minAltitude; + world.PlaceDungeons(random, x, y, z); + } - return true; + @Override + public ResourceType getType() + { + return ResourceType.biomeConfigResource; } @Override - protected String WriteString(Resource res, String blockSources) + public String makeString() { - return res.Frequency + "","" + res.Rarity + "","" + res.MinAltitude + "","" + res.MaxAltitude; + return ""Dungeon("" + frequency + "","" + rarity + "","" + minAltitude + "","" + maxAltitude + "")""; } } \ No newline at end of file diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/GrassGen.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/GrassGen.java index 0bed67e32..79c895dcc 100644 --- a/common/src/com/khorn/terraincontrol/generator/resourcegens/GrassGen.java +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/GrassGen.java @@ -1,60 +1,74 @@ package com.khorn.terraincontrol.generator.resourcegens; -import com.khorn.terraincontrol.configuration.BiomeConfig; import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.exception.InvalidResourceException; import com.khorn.terraincontrol.DefaultMaterial; import com.khorn.terraincontrol.LocalWorld; +import java.util.ArrayList; +import java.util.List; import java.util.Random; -public class GrassGen extends ResourceGenBase +public class GrassGen extends Resource { + private int blockId; + private int blockData; + private List sourceBlocks; + + @Override + public void load(List args) throws InvalidResourceException + { + if (args.size() < 5) + { + throw new InvalidResourceException(""Too few arguments supplied""); + } + blockId = getBlockId(args.get(0)); + blockData = getInt(args.get(1), 0, 16); + frequency = getInt(args.get(2), 1, 500); + rarity = getInt(args.get(3), 1, 100); + sourceBlocks = new ArrayList(); + for (int i = 4; i < args.size(); i++) + { + sourceBlocks.add(getBlockId(args.get(i))); + } + } + @Override - public void Process(LocalWorld world, Random rand, Resource res, int _x, int _z) + public void spawn(LocalWorld world, Random random, int x, int z) { + // Handled by process(). + } - for (int t = 0; t < res.Frequency; t++) + @Override + public void process(LocalWorld world, Random random, int chunkX, int chunkZ) + { + for (int t = 0; t < frequency; t++) { - if (rand.nextInt(100) >= res.Rarity) + if (random.nextInt(100) >= rarity) continue; - int x = _x + rand.nextInt(16) + 8; - int y = world.getHeight(); - int z = _z + rand.nextInt(16) + 8; + int x = chunkX * 16 + random.nextInt(16) + 8; + int z = chunkZ * 16 + random.nextInt(16) + 8; + int y = world.getHighestBlockYAt(x, z); int i; while ((((i = world.getTypeId(x, y, z)) == 0) || (i == DefaultMaterial.LEAVES.id)) && (y > 0)) y--; - if ((!world.isEmpty(x, y + 1, z)) || (!res.CheckSourceId(world.getTypeId(x, y, z)))) + if ((!world.isEmpty(x, y + 1, z)) || (!sourceBlocks.contains(world.getTypeId(x, y, z)))) continue; - world.setBlock(x, y + 1, z, res.BlockId, res.BlockData, false, false, false); + world.setBlock(x, y + 1, z, blockId, blockData, false, false, false); } } @Override - protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, int z) + public ResourceType getType() { - - } - - @Override - protected boolean ReadString(Resource res, String[] Props, BiomeConfig biomeConfig) throws NumberFormatException - { - res.BlockId = CheckBlock(Props[0]); - res.BlockData = CheckValue(Props[1], 0, 16); - res.Frequency = CheckValue(Props[2], 1, 500); - res.Rarity = CheckValue(Props[3], 0, 100); - - res.SourceBlockId = new int[Props.length - 4]; - for (int i = 4; i < Props.length; i++) - res.SourceBlockId[i - 4] = CheckBlock(Props[i]); - - return true; + return ResourceType.biomeConfigResource; } @Override - protected String WriteString(Resource res, String blockSources) + public String makeString() { - return res.BlockIdToName(res.BlockId) + "","" + res.BlockData + "","" + res.Frequency + "","" + res.Rarity + blockSources; + return ""Grass("" + makeMaterial(blockId) + "","" + blockData + "","" + frequency + "","" + rarity + makeMaterial(sourceBlocks) + "")""; } } \ No newline at end of file diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/LiquidGen.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/LiquidGen.java index 00a6cb9f7..1688c7584 100644 --- a/common/src/com/khorn/terraincontrol/generator/resourcegens/LiquidGen.java +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/LiquidGen.java @@ -1,85 +1,97 @@ package com.khorn.terraincontrol.generator.resourcegens; import com.khorn.terraincontrol.LocalWorld; +import com.khorn.terraincontrol.TerrainControl; -import com.khorn.terraincontrol.configuration.BiomeConfig; import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.exception.InvalidResourceException; +import java.util.ArrayList; +import java.util.List; import java.util.Random; -public class LiquidGen extends ResourceGenBase +public class LiquidGen extends Resource { + private int blockId; + private int blockData; + private List sourceBlocks; + private int minAltitude; + private int maxAltitude; + @Override - protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, int z) + public void spawn(LocalWorld world, Random rand, int x, int z) { - int y = rand.nextInt(res.MaxAltitude - res.MinAltitude) + res.MinAltitude; + int y = rand.nextInt(maxAltitude - minAltitude) + minAltitude; - if (res.CheckSourceId(world.getTypeId(x, y + 1, z))) + if (sourceBlocks.contains(world.getTypeId(x, y + 1, z))) return; - if (res.CheckSourceId(world.getTypeId(x, y - 1, z))) + if (sourceBlocks.contains(world.getTypeId(x, y - 1, z))) return; - if ((world.getTypeId(x, y, z) != 0) && (res.CheckSourceId(world.getTypeId(x, y, z)))) + if ((world.getTypeId(x, y, z) != 0) && (sourceBlocks.contains(world.getTypeId(x, y, z)))) return; - int i = 0; int j = 0; int tempBlock = world.getTypeId(x - 1, y, z); - i = (res.CheckSourceId(tempBlock)) ? i + 1 : i; + i = (sourceBlocks.contains(tempBlock)) ? i + 1 : i; j = (tempBlock == 0) ? j + 1 : j; tempBlock = world.getTypeId(x + 1, y, z); - i = (res.CheckSourceId(tempBlock)) ? i + 1 : i; + i = (sourceBlocks.contains(tempBlock)) ? i + 1 : i; j = (tempBlock == 0) ? j + 1 : j; tempBlock = world.getTypeId(x, y, z - 1); - i = (res.CheckSourceId(tempBlock)) ? i + 1 : i; + i = (sourceBlocks.contains(tempBlock)) ? i + 1 : i; j = (tempBlock == 0) ? j + 1 : j; tempBlock = world.getTypeId(x, y, z + 1); - i = (res.CheckSourceId(tempBlock)) ? i + 1 : i; + i = (sourceBlocks.contains(tempBlock)) ? i + 1 : i; j = (tempBlock == 0) ? j + 1 : j; - if ((i == 3) && (j == 1)) { - world.setBlock(x, y, z, res.BlockId, 0, true, true, true); - //this.world.f = true; - //Block.byId[res.BlockId].a(this.world, x, y, z, this.rand); - //this.world.f = false; + world.setBlock(x, y, z, blockId, 0, true, true, true); + // this.world.f = true; + // Block.byId[res.BlockId].a(this.world, x, y, z, this.rand); + // this.world.f = false; } } @Override - protected boolean ReadString(Resource res, String[] Props, BiomeConfig biomeConfig) throws NumberFormatException + public void load(List args) throws InvalidResourceException { - res.BlockId = CheckBlock(Props[0]); - res.Frequency = CheckValue(Props[1], 1, 5000); - res.Rarity = CheckValue(Props[2], 0, 100); - res.MinAltitude = CheckValue(Props[3], 0, biomeConfig.worldConfig.WorldHeight); - res.MaxAltitude = CheckValue(Props[4], 0, biomeConfig.worldConfig.WorldHeight, res.MinAltitude); - - res.SourceBlockId = new int[Props.length - 5]; - for (int i = 5; i < Props.length; i++) - res.SourceBlockId[i - 5] = CheckBlock(Props[i]); + if (args.size() < 6) + { + throw new InvalidResourceException(""Too few arguments supplied""); + } + blockId = getBlockId(args.get(0)); + blockData = getBlockData(args.get(0)); + frequency = getInt(args.get(1), 1, 5000); + rarity = getInt(args.get(2), 1, 100); + minAltitude = getInt(args.get(3), TerrainControl.worldDepth, TerrainControl.worldHeight); + maxAltitude = getInt(args.get(4), minAltitude + 1, TerrainControl.worldHeight); + sourceBlocks = new ArrayList(); + for (int i = 5; i < args.size(); i++) + { + sourceBlocks.add(getBlockId(args.get(i))); + } + } - return true; + @Override + public ResourceType getType() + { + return ResourceType.biomeConfigResource; } @Override - protected String WriteString(Resource res, String blockSources) + public String makeString() { - String blockId = res.BlockIdToName(res.BlockId); - if (res.BlockData > 0) - { - blockId += ""."" + res.BlockData; - } - return blockId + "","" + res.Frequency + "","" + res.Rarity + "","" + res.MinAltitude + "","" + res.MaxAltitude + blockSources; + return ""Liquid("" + makeMaterial(blockId, blockData) + "","" + frequency + "","" + rarity + "","" + minAltitude + "","" + maxAltitude + makeMaterial(sourceBlocks) + "")""; } } \ No newline at end of file diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/OreGen.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/OreGen.java index 5511da455..222d0fcec 100644 --- a/common/src/com/khorn/terraincontrol/generator/resourcegens/OreGen.java +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/OreGen.java @@ -1,38 +1,48 @@ package com.khorn.terraincontrol.generator.resourcegens; -import com.khorn.terraincontrol.configuration.BiomeConfig; -import com.khorn.terraincontrol.configuration.Resource; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + import com.khorn.terraincontrol.LocalWorld; +import com.khorn.terraincontrol.TerrainControl; +import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.exception.InvalidResourceException; import com.khorn.terraincontrol.util.MathHelper; -import java.util.Random; - -public class OreGen extends ResourceGenBase +public class OreGen extends Resource { + private int blockId; + private int blockData; + private int minAltitude; + private int maxAltitude; + private int maxSize; + private List sourceBlocks; + @Override - protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, int z) + public void spawn(LocalWorld world, Random rand, int x, int z) { - int y = rand.nextInt(res.MaxAltitude - res.MinAltitude) + res.MinAltitude; + int y = rand.nextInt(maxAltitude - minAltitude) + minAltitude; float f = rand.nextFloat() * 3.141593F; - double d1 = x + 8 + MathHelper.sin(f) * res.MaxSize / 8.0F; - double d2 = x + 8 - MathHelper.sin(f) * res.MaxSize / 8.0F; - double d3 = z + 8 + MathHelper.cos(f) * res.MaxSize / 8.0F; - double d4 = z + 8 - MathHelper.cos(f) * res.MaxSize / 8.0F; + double d1 = x + 8 + MathHelper.sin(f) * maxSize / 8.0F; + double d2 = x + 8 - MathHelper.sin(f) * maxSize / 8.0F; + double d3 = z + 8 + MathHelper.cos(f) * maxSize / 8.0F; + double d4 = z + 8 - MathHelper.cos(f) * maxSize / 8.0F; double d5 = y + rand.nextInt(3) - 2; double d6 = y + rand.nextInt(3) - 2; - for (int i = 0; i <= res.MaxSize; i++) + for (int i = 0; i <= maxSize; i++) { - double d7 = d1 + (d2 - d1) * i / res.MaxSize; - double d8 = d5 + (d6 - d5) * i / res.MaxSize; - double d9 = d3 + (d4 - d3) * i / res.MaxSize; + double d7 = d1 + (d2 - d1) * i / maxSize; + double d8 = d5 + (d6 - d5) * i / maxSize; + double d9 = d3 + (d4 - d3) * i / maxSize; - double d10 = rand.nextDouble() * res.MaxSize / 16.0D; - double d11 = (MathHelper.sin(i * 3.141593F / res.MaxSize) + 1.0F) * d10 + 1.0D; - double d12 = (MathHelper.sin(i * 3.141593F / res.MaxSize) + 1.0F) * d10 + 1.0D; + double d10 = rand.nextDouble() * maxSize / 16.0D; + double d11 = (MathHelper.sin(i * 3.141593F / maxSize) + 1.0F) * d10 + 1.0D; + double d12 = (MathHelper.sin(i * 3.141593F / maxSize) + 1.0F) * d10 + 1.0D; int j = MathHelper.floor(d7 - d11 / 2.0D); int k = MathHelper.floor(d8 - d12 / 2.0D); @@ -55,15 +65,9 @@ protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, for (int i5 = m; i5 <= i2; i5++) { double d15 = (i5 + 0.5D - d9) / (d11 / 2.0D); - if ((d13 * d13 + d14 * d14 + d15 * d15 < 1.0D) && res.CheckSourceId(world.getTypeId(i3, i4, i5))) + if ((d13 * d13 + d14 * d14 + d15 * d15 < 1.0D) && sourceBlocks.contains(world.getTypeId(i3, i4, i5))) { - if (res.BlockData > 0) - { - world.setBlock(i3, i4, i5, res.BlockId, res.BlockData, false, false, false); - } else - { - world.setBlock(i3, i4, i5, res.BlockId, 0, false, false, false); - } + world.setBlock(i3, i4, i5, blockId, blockData, false, false, false); } } } @@ -74,40 +78,35 @@ protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, } @Override - protected boolean ReadString(Resource res, String[] Props, BiomeConfig biomeConfig) throws NumberFormatException + public void load(List args) throws InvalidResourceException { - if (Props[0].contains(""."")) + if (args.size() < 7) { - String[] block = Props[0].split(""\\.""); - res.BlockId = CheckBlock(block[0]); - res.BlockData = CheckValue(block[1], 0, 16); - } else + throw new InvalidResourceException(""Too few arguments supplied""); + } + blockId = getBlockId(args.get(0)); + blockData = getBlockData(args.get(0)); + maxSize = getInt(args.get(1), 1, 128); + frequency = getInt(args.get(2), 1, 100); + rarity = getInt(args.get(3), 1, 100); + minAltitude = getInt(args.get(4), TerrainControl.worldDepth, TerrainControl.worldHeight); + maxAltitude = getInt(args.get(5), minAltitude + 1, TerrainControl.worldHeight); + sourceBlocks = new ArrayList(); + for (int i = 6; i < args.size(); i++) { - res.BlockId = CheckBlock(Props[0]); + sourceBlocks.add(getBlockId(args.get(i))); } + } - res.MaxSize = CheckValue(Props[1], 1, 128); - res.Frequency = CheckValue(Props[2], 1, 100); - res.Rarity = CheckValue(Props[3], 0, 100); - res.MinAltitude = CheckValue(Props[4], 0, biomeConfig.worldConfig.WorldHeight); - res.MaxAltitude = CheckValue(Props[5], 0, biomeConfig.worldConfig.WorldHeight, res.MinAltitude); - - res.SourceBlockId = new int[Props.length - 6]; - for (int i = 6; i < Props.length; i++) - res.SourceBlockId[i - 6] = CheckBlock(Props[i]); - - return true; - + @Override + public ResourceType getType() + { + return ResourceType.biomeConfigResource; } @Override - protected String WriteString(Resource res, String blockSources) + public String makeString() { - String blockId = res.BlockIdToName(res.BlockId); - if (res.BlockData > 0) - { - blockId += ""."" + res.BlockData; - } - return blockId + "","" + res.MaxSize + "","" + res.Frequency + "","" + res.Rarity + "","" + res.MinAltitude + "","" + res.MaxAltitude + blockSources; + return ""Ore("" + makeMaterial(blockId, blockData) + "","" + maxSize + "","" + frequency + "","" + rarity + "","" + minAltitude + "","" + maxAltitude + makeMaterial(sourceBlocks) + "")""; } } diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/PlantGen.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/PlantGen.java index 9d5af4050..2aae19816 100644 --- a/common/src/com/khorn/terraincontrol/generator/resourcegens/PlantGen.java +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/PlantGen.java @@ -1,69 +1,68 @@ package com.khorn.terraincontrol.generator.resourcegens; -import com.khorn.terraincontrol.configuration.BiomeConfig; import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.exception.InvalidResourceException; import com.khorn.terraincontrol.LocalWorld; +import com.khorn.terraincontrol.TerrainControl; +import java.util.ArrayList; +import java.util.List; import java.util.Random; -public class PlantGen extends ResourceGenBase +public class PlantGen extends Resource { + private int blockId; + private int blockData; + private int minAltitude; + private int maxAltitude; + private List sourceBlocks; + @Override - protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, int z) + public void spawn(LocalWorld world, Random rand, int x, int z) { - int y = rand.nextInt(res.MaxAltitude - res.MinAltitude) + res.MinAltitude; + int y = rand.nextInt(maxAltitude - minAltitude) + minAltitude; for (int i = 0; i < 64; i++) { int j = x + rand.nextInt(8) - rand.nextInt(8); int k = y + rand.nextInt(4) - rand.nextInt(4); int m = z + rand.nextInt(8) - rand.nextInt(8); - if ((!world.isEmpty(j, k, m)) || (!res.CheckSourceId(world.getTypeId(j, k - 1, m)))) + if ((!world.isEmpty(j, k, m)) || (!sourceBlocks.contains(world.getTypeId(j, k - 1, m)))) continue; - if (res.BlockData > 0) - { - world.setBlock(j, k, m, res.BlockId, res.BlockData, false, false, false); - } else - { - world.setBlock(j, k, m, res.BlockId, 0, false, false, false); - } + world.setBlock(j, k, m, blockId, blockData, false, false, false); } } @Override - protected boolean ReadString(Resource res, String[] Props, BiomeConfig biomeConfig) throws NumberFormatException + public void load(List args) throws InvalidResourceException { - if (Props[0].contains(""."")) + if (args.size() < 6) { - String[] block = Props[0].split(""\\.""); - res.BlockId = CheckBlock(block[0]); - res.BlockData = CheckValue(block[1], 0, 16); - } else + throw new InvalidResourceException(""Too few arguments supplied""); + } + blockId = getBlockId(args.get(0)); + blockData = getBlockData(args.get(0)); + frequency = getInt(args.get(1), 1, 100); + rarity = getInt(args.get(2), 1, 100); + minAltitude = getInt(args.get(3), TerrainControl.worldDepth, TerrainControl.worldHeight); + maxAltitude = getInt(args.get(4), minAltitude + 1, TerrainControl.worldHeight); + sourceBlocks = new ArrayList(); + for (int i = 5; i < args.size(); i++) { - res.BlockId = CheckBlock(Props[0]); + sourceBlocks.add(getBlockId(args.get(i))); } + } - res.Frequency = CheckValue(Props[1], 1, 100); - res.Rarity = CheckValue(Props[2], 0, 100); - res.MinAltitude = CheckValue(Props[3], 0, biomeConfig.worldConfig.WorldHeight); - res.MaxAltitude = CheckValue(Props[4], 0, biomeConfig.worldConfig.WorldHeight, res.MinAltitude); - - res.SourceBlockId = new int[Props.length - 5]; - for (int i = 5; i < Props.length; i++) - res.SourceBlockId[i - 5] = CheckBlock(Props[i]); - - return true; + @Override + public ResourceType getType() + { + return ResourceType.biomeConfigResource; } @Override - protected String WriteString(Resource res, String blockSources) + public String makeString() { - String blockId = res.BlockIdToName(res.BlockId); - if (res.BlockData > 0) - { - blockId += ""."" + res.BlockData; - } - return blockId + "","" + res.Frequency + "","" + res.Rarity + "","" + res.MinAltitude + "","" + res.MaxAltitude + blockSources; + return ""Plant("" + makeMaterial(blockId, blockData) + "","" + frequency + "","" + rarity + "","" + minAltitude + "","" + maxAltitude + makeMaterial(sourceBlocks) + "")""; } } \ No newline at end of file diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/ReedGen.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/ReedGen.java index 89cf0f368..e10d6f272 100644 --- a/common/src/com/khorn/terraincontrol/generator/resourcegens/ReedGen.java +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/ReedGen.java @@ -1,65 +1,73 @@ package com.khorn.terraincontrol.generator.resourcegens; import com.khorn.terraincontrol.LocalWorld; -import com.khorn.terraincontrol.configuration.BiomeConfig; +import com.khorn.terraincontrol.TerrainControl; import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.exception.InvalidResourceException; +import java.util.ArrayList; +import java.util.List; import java.util.Random; -public class ReedGen extends ResourceGenBase +public class ReedGen extends Resource { + private int blockId; + private int blockData; + private int minAltitude; + private int maxAltitude; + private List sourceBlocks; + @Override - protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, int z) + public void spawn(LocalWorld world, Random rand, int x, int z) { int y = world.getHighestBlockYAt(x, z); - if (y > res.MaxAltitude || y < res.MinAltitude || (!world.getMaterial(x - 1, y - 1, z).isLiquid() && !world.getMaterial(x + 1, y - 1, z).isLiquid() && !world.getMaterial(x, y - 1, z - 1).isLiquid() && !world.getMaterial(x, y - 1, z + 1).isLiquid())) + if (y > maxAltitude + || y < minAltitude + || (!world.getMaterial(x - 1, y - 1, z).isLiquid() && !world.getMaterial(x + 1, y - 1, z).isLiquid() && !world.getMaterial(x, y - 1, z - 1).isLiquid() && !world.getMaterial(x, y - 1, + z + 1).isLiquid())) { return; } - if (!res.CheckSourceId(world.getTypeId(x, y - 1, z))) + if (!sourceBlocks.contains(world.getTypeId(x, y - 1, z))) { return; } - + int n = 1 + rand.nextInt(2); for (int i1 = 0; i1 < n; i1++) - world.setBlock(x, y + i1, z, res.BlockId, res.BlockData, false, false, false); + world.setBlock(x, y + i1, z, blockId, blockData, false, false, false); } @Override - protected boolean ReadString(Resource res, String[] Props, BiomeConfig biomeConfig) throws NumberFormatException + public void load(List args) throws InvalidResourceException { - if (Props[0].contains(""."")) + if (args.size() < 6) { - String[] block = Props[0].split(""\\.""); - res.BlockId = CheckBlock(block[0]); - res.BlockData = CheckValue(block[1], 0, 16); - } else + throw new InvalidResourceException(""Too few arguments supplied""); + } + blockId = getBlockId(args.get(0)); + blockData = getBlockData(args.get(0)); + frequency = getInt(args.get(1), 1, 100); + rarity = getInt(args.get(2), 1, 100); + minAltitude = getInt(args.get(3), TerrainControl.worldDepth, TerrainControl.worldHeight); + maxAltitude = getInt(args.get(4), minAltitude + 1, TerrainControl.worldHeight); + sourceBlocks = new ArrayList(); + for (int i = 5; i < args.size(); i++) { - res.BlockId = CheckBlock(Props[0]); + sourceBlocks.add(getBlockId(args.get(i))); } + } - res.Frequency = CheckValue(Props[1], 1, 100); - res.Rarity = CheckValue(Props[2], 0, 100); - res.MinAltitude = CheckValue(Props[3], 0, biomeConfig.worldConfig.WorldHeight); - res.MaxAltitude = CheckValue(Props[4], 0, biomeConfig.worldConfig.WorldHeight, res.MinAltitude); - - res.SourceBlockId = new int[Props.length - 5]; - for (int i = 5; i < Props.length; i++) - res.SourceBlockId[i - 5] = CheckBlock(Props[i]); - - return true; + @Override + public ResourceType getType() + { + return ResourceType.biomeConfigResource; } @Override - protected String WriteString(Resource res, String blockSources) + public String makeString() { - String blockId = res.BlockIdToName(res.BlockId); - if (res.BlockData > 0) - { - blockId += ""."" + res.BlockData; - } - return blockId + "","" + res.Frequency + "","" + res.Rarity + "","" + res.MinAltitude + "","" + res.MaxAltitude + blockSources; + return ""Reed("" + makeMaterial(blockId, blockData) + "","" + frequency + "","" + rarity + "","" + minAltitude + "","" + maxAltitude + makeMaterial(sourceBlocks) + "")""; } } \ No newline at end of file diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/ResourceGenBase.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/ResourceGenBase.java deleted file mode 100644 index 3b0e7dcc0..000000000 --- a/common/src/com/khorn/terraincontrol/generator/resourcegens/ResourceGenBase.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.khorn.terraincontrol.generator.resourcegens; - -import com.khorn.terraincontrol.DefaultMaterial; -import com.khorn.terraincontrol.configuration.BiomeConfig; -import com.khorn.terraincontrol.configuration.Resource; -import com.khorn.terraincontrol.LocalWorld; - -import java.util.Random; - -public abstract class ResourceGenBase -{ - public void Process(LocalWorld world, Random rand, Resource res, int _x, int _z) - { - for (int t = 0; t < res.Frequency; t++) - { - if (rand.nextInt(100) > res.Rarity) - continue; - int x = _x + rand.nextInt(16) + 8; - int z = _z + rand.nextInt(16) + 8; - SpawnResource(world, rand, res, x, z); - } - - } - - protected abstract void SpawnResource(LocalWorld world, Random rand, Resource res, int x, int z); - - public boolean ReadFromString(Resource res, String[] line, BiomeConfig biomeConfig) - { - if (line.length < res.Type.MinProperties) - return false; - try - { - return this.ReadString(res, line, biomeConfig); - - } catch (NumberFormatException e) - { - return false; - } - } - - // ToDo make it more logical. - public String WriteToString(Resource res) - { - String sources = """"; - for (int id : res.SourceBlockId) - sources += "","" + res.BlockIdToName(id); - - return res.Type.name() + ""("" + this.WriteString(res, sources) + "")""; - } - - public String WriteSettingOnly(Resource res) - { - String sources = """"; - for (int id : res.SourceBlockId) - sources += "","" + res.BlockIdToName(id); - return this.WriteString(res, sources); - } - - protected abstract String WriteString(Resource res, String blockSources); - - protected abstract boolean ReadString(Resource res, String[] Props, BiomeConfig biomeConfig) throws NumberFormatException; - - protected int CheckValue(String str, int min, int max) throws NumberFormatException - { - int value = Integer.valueOf(str); - if (value > max) - return max; - else if (value < min) - return min; - else - return value; - } - - protected int CheckValue(String str, int min, int max, int minValue) throws NumberFormatException - { - int value = CheckValue(str, min, max); - - if (value < minValue) - return minValue + 1; - else - return value; - } - - protected int CheckBlock(String block) throws NumberFormatException - { - DefaultMaterial mat = DefaultMaterial.getMaterial(block); - if (mat != null) - return mat.id; - - return CheckValue(block, 0, 256); - } -} \ No newline at end of file diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/ResourceType.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/ResourceType.java index 73097162a..1489912f6 100644 --- a/common/src/com/khorn/terraincontrol/generator/resourcegens/ResourceType.java +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/ResourceType.java @@ -1,49 +1,6 @@ package com.khorn.terraincontrol.generator.resourcegens; -import com.khorn.terraincontrol.customobjects.CustomObjectGen; - public enum ResourceType { - Ore(OreGen.class, false, 7), - UnderWaterOre(UnderWaterOreGen.class, 5), - Plant(PlantGen.class, 6), - Liquid(LiquidGen.class, 6), - Grass(GrassGen.class, 5), - Reed(ReedGen.class, 6), - Cactus(CactusGen.class, 6), - Dungeon(DungeonGen.class, 4), - Tree(TreeGen.class, 3), - Sapling(TreeGen.class, 3), - CustomObject(CustomObjectGen.class, 0), - UnderGroundLake(UndergroundLakeGen.class, 6), - AboveWaterRes(AboveWaterGen.class, 3), - Vines(VinesGen.class, 4), - SmallLake(SmallLakeGen.class,5); - - public ResourceGenBase Generator; - public final boolean CreateNewChunks; - public final int MinProperties; - - - private ResourceType(Class c, int props) - { - this(c, true, props); - } - - private ResourceType(Class c, boolean createNewChunks, int props) - { - this.CreateNewChunks = createNewChunks; - this.MinProperties = props; - try - { - Generator = c.newInstance(); - - } catch (InstantiationException e) - { - e.printStackTrace(); - } catch (IllegalAccessException e) - { - e.printStackTrace(); - } - } + biomeConfigResource, saplingResource } diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/ResourcesManager.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/ResourcesManager.java new file mode 100644 index 000000000..349a07313 --- /dev/null +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/ResourcesManager.java @@ -0,0 +1,88 @@ +package com.khorn.terraincontrol.generator.resourcegens; + +import java.util.List; +import java.util.Map; + +import com.khorn.terraincontrol.TerrainControl; +import com.khorn.terraincontrol.configuration.BiomeConfig; +import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.configuration.WorldConfig; +import com.khorn.terraincontrol.exception.InvalidResourceException; + +public class ResourcesManager +{ + private Map> resourceTypes; + + public ResourcesManager(Map> resourceTypes) + { + // Also store in this class + this.resourceTypes = resourceTypes; + + // Add vanilla resources + put(""AboveWaterRes"", AboveWaterGen.class); + put(""Cactus"", CactusGen.class); + put(""CustomObject"", CustomObjectGen.class); + put(""Dungeon"", DungeonGen.class); + put(""Grass"", GrassGen.class); + put(""Liquid"", LiquidGen.class); + put(""Ore"", OreGen.class); + put(""Plant"", PlantGen.class); + put(""Reed"", ReedGen.class); + put(""SmallLake"", SmallLakeGen.class); + put(""Tree"", TreeGen.class); + put(""UndergroundLake"", UndergroundLakeGen.class); + put(""UnderWaterOre"", UnderWaterOreGen.class); + put(""Vines"", VinesGen.class); + } + + public void put(String name, Class value) + { + resourceTypes.put(name.toLowerCase(), value); + } + + /** + * Creates a resource with the specified name. + * + * @param name + * Name of the resource, like Ore + * @param args + * String representation of the args. + * @return The resource, or null of no matching resource could be found. + */ + public Resource getResource(String name, BiomeConfig biomeConfig, List args) + { + if (resourceTypes.containsKey(name.toLowerCase())) + { + Resource resource; + try + { + resource = resourceTypes.get(name.toLowerCase()).newInstance(); + } catch (InstantiationException e) + { + TerrainControl.log(""Reflection error while loading the resources: "" + e.getMessage()); + e.printStackTrace(); + return null; + } catch (IllegalAccessException e) + { + TerrainControl.log(""Reflection error while loading the resources: "" + e.getMessage()); + e.printStackTrace(); + return null; + } + resource.setWorldConfig(biomeConfig.worldConfig); + try + { + resource.load(args); + } catch (InvalidResourceException e) + { + TerrainControl.log(""Invalid resource "" + name + "" in "" + biomeConfig.Name + "": "" + e.getMessage()); + return null; + } + + return resource; + + } + + return null; + } + +} diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/SaplingGen.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/SaplingGen.java new file mode 100644 index 000000000..7531cb845 --- /dev/null +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/SaplingGen.java @@ -0,0 +1,102 @@ +package com.khorn.terraincontrol.generator.resourcegens; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import com.khorn.terraincontrol.LocalWorld; +import com.khorn.terraincontrol.TerrainControl; +import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.customobjects.CustomObject; +import com.khorn.terraincontrol.exception.InvalidResourceException; + +public class SaplingGen extends Resource +{ + public List trees; + public List treeNames; + public List treeChances; + public int saplingType; + + @Override + public void process(LocalWorld world, Random random, int chunkX, int chunkZ) + { + // Left blank, as it shouldn't spawn anything. + } + + @Override + public void load(List args) throws InvalidResourceException + { + assureSize(3, args); + + if (args.get(0).equalsIgnoreCase(""All"")) + { + saplingType = -1; + } else + { + saplingType = getInt(args.get(0), -1, 3); + } + + trees = new ArrayList(); + treeNames = new ArrayList(); + treeChances = new ArrayList(); + + for (int i = 1; i < args.size() - 1; i += 2) + { + CustomObject object = TerrainControl.getCustomObjectManager().getObjectFromString(args.get(i), worldConfig); + if (object == null) + { + throw new InvalidResourceException(""Custom object "" + args.get(i) + "" not found!""); + } + if(!object.canSpawnAsTree()) + { + throw new InvalidResourceException(""Custom object "" + args.get(i) + "" is not a tree!""); + } + trees.add(object); + treeNames.add(args.get(i)); + treeChances.add(getInt(args.get(i + 1), 1, 100)); + } + } + + @Override + public ResourceType getType() + { + return ResourceType.saplingResource; + } + + @Override + public String makeString() + { + String output = ""Sapling("" + saplingType; + if (saplingType == -1) + { + output = ""Sapling(All""; + } + for (int i = 0; i < treeNames.size(); i++) + { + output += "","" + treeNames.get(i) + "","" + treeChances.get(i); + } + return output + "")""; + } + + @Override + public void spawn(LocalWorld world, Random random, int x, int z) + { + // Left blank, as process() already handles this + } + + public boolean growSapling(LocalWorld world, Random random, int x, int y, int z) + { + for (int treeNumber = 0; treeNumber < trees.size(); treeNumber++) + { + if (random.nextInt(100) < treeChances.get(treeNumber)) + { + if (trees.get(treeNumber).spawnAsTree(world, random, x, z)) + { + // Success! + return true; + } + } + } + return false; + } +} diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/SmallLakeGen.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/SmallLakeGen.java index 40baafeb7..09105f5ce 100644 --- a/common/src/com/khorn/terraincontrol/generator/resourcegens/SmallLakeGen.java +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/SmallLakeGen.java @@ -1,25 +1,30 @@ package com.khorn.terraincontrol.generator.resourcegens; +import java.util.List; +import java.util.Random; + import com.khorn.terraincontrol.DefaultMaterial; import com.khorn.terraincontrol.LocalWorld; -import com.khorn.terraincontrol.configuration.BiomeConfig; +import com.khorn.terraincontrol.TerrainControl; import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.exception.InvalidResourceException; -import java.util.Random; - -public class SmallLakeGen extends ResourceGenBase +public class SmallLakeGen extends Resource { private final boolean[] BooleanBuffer = new boolean[2048]; - + private int blockId; + private int blockData; + private int minAltitude; + private int maxAltitude; @Override - protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, int z) + public void spawn(LocalWorld world, Random rand, int x, int z) { x -= 8; z -= 8; - int y = rand.nextInt(res.MaxAltitude - res.MinAltitude) + res.MinAltitude; + int y = rand.nextInt(maxAltitude - minAltitude) + minAltitude; // Search any free space while ((y > 5) && (world.isEmpty(x, y, z))) @@ -31,7 +36,6 @@ protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, // y = floor y -= 4; - synchronized (BooleanBuffer) { boolean[] BooleanBuffer = new boolean[2048]; @@ -67,14 +71,17 @@ protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, { for (i2 = 0; i2 < 8; i2++) { - boolean flag = (!BooleanBuffer[((j * 16 + i1) * 8 + i2)]) && (((j < 15) && (BooleanBuffer[(((j + 1) * 16 + i1) * 8 + i2)])) || ((j > 0) && (BooleanBuffer[(((j - 1) * 16 + i1) * 8 + i2)])) || ((i1 < 15) && (BooleanBuffer[((j * 16 + (i1 + 1)) * 8 + i2)])) || ((i1 > 0) && (BooleanBuffer[((j * 16 + (i1 - 1)) * 8 + i2)])) || ((i2 < 7) && (BooleanBuffer[((j * 16 + i1) * 8 + (i2 + 1))])) || ((i2 > 0) && (BooleanBuffer[((j * 16 + i1) * 8 + (i2 - 1))]))); + boolean flag = (!BooleanBuffer[((j * 16 + i1) * 8 + i2)]) + && (((j < 15) && (BooleanBuffer[(((j + 1) * 16 + i1) * 8 + i2)])) || ((j > 0) && (BooleanBuffer[(((j - 1) * 16 + i1) * 8 + i2)])) + || ((i1 < 15) && (BooleanBuffer[((j * 16 + (i1 + 1)) * 8 + i2)])) || ((i1 > 0) && (BooleanBuffer[((j * 16 + (i1 - 1)) * 8 + i2)])) + || ((i2 < 7) && (BooleanBuffer[((j * 16 + i1) * 8 + (i2 + 1))])) || ((i2 > 0) && (BooleanBuffer[((j * 16 + i1) * 8 + (i2 - 1))]))); if (flag) { DefaultMaterial localMaterial = world.getMaterial(x + j, y + i2, z + i1); if ((i2 >= 4) && (localMaterial.isLiquid())) return; - if ((i2 < 4) && (!localMaterial.isSolid()) && (world.getTypeId(x + j, y + i2, z + i1) != res.BlockId)) + if ((i2 < 4) && (!localMaterial.isSolid()) && (world.getTypeId(x + j, y + i2, z + i1) != blockId)) return; } } @@ -90,7 +97,7 @@ protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, { if (BooleanBuffer[((j * 16 + i1) * 8 + i2)]) { - world.setBlock(x + j, y + i2, z + i1, res.BlockId, res.BlockData); + world.setBlock(x + j, y + i2, z + i1, blockId, blockData); BooleanBuffer[((j * 16 + i1) * 8 + i2)] = false; } } @@ -104,77 +111,31 @@ protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, } } } - /* - for (j = 0; j < 16; j++) { - for (i1 = 0; i1 < 16; i1++) { - for (i2 = 4; i2 < 8; i2++) { - if ((BooleanBuffer[((j * 16 + i1) * 8 + i2)] == 0) || - (paramWorld.getTypeId(x + j, y + i2 - 1, z + i1) != Block.DIRT.id) || (paramWorld.a(EnumSkyBlock.SKY, x + j, y + i2, z + i1) <= 0)) continue; - BiomeBase localBiomeBase = paramWorld.getBiome(x + j, z + i1); - if (localBiomeBase.A == Block.MYCEL.id) paramWorld.setRawTypeId(x + j, y + i2 - 1, z + i1, Block.MYCEL.id); else { - paramWorld.setRawTypeId(x + j, y + i2 - 1, z + i1, Block.GRASS.id); - } - } - } - - } - - if (Block.byId[this.a].material == Material.LAVA) { - for (j = 0; j < 16; j++) { - for (i1 = 0; i1 < 16; i1++) { - for (i2 = 0; i2 < 8; i2++) { - int i4 = (BooleanBuffer[((j * 16 + i1) * 8 + i2)] == 0) && (((j < 15) && (BooleanBuffer[(((j + 1) * 16 + i1) * 8 + i2)] != 0)) || ((j > 0) && (BooleanBuffer[(((j - 1) * 16 + i1) * 8 + i2)] != 0)) || ((i1 < 15) && (BooleanBuffer[((j * 16 + (i1 + 1)) * 8 + i2)] != 0)) || ((i1 > 0) && (BooleanBuffer[((j * 16 + (i1 - 1)) * 8 + i2)] != 0)) || ((i2 < 7) && (BooleanBuffer[((j * 16 + i1) * 8 + (i2 + 1))] != 0)) || ((i2 > 0) && (BooleanBuffer[((j * 16 + i1) * 8 + (i2 - 1))] != 0))) ? 1 : 0; - - if ((i4 == 0) || - ((i2 >= 4) && (rand.nextInt(2) == 0)) || (!paramWorld.getMaterial(x + j, y + i2, z + i1).isBuildable())) continue; - paramWorld.setRawTypeId(x + j, y + i2, z + i1, Block.STONE.id); - } - } - - } - - } - - if (Block.byId[this.a].material == Material.WATER) { - for (j = 0; j < 16; j++) { - for (i1 = 0; i1 < 16; i1++) { - i2 = 4; - if (!paramWorld.s(x + j, y + i2, z + i1)) continue; paramWorld.setRawTypeId(x + j, y + i2, z + i1, Block.ICE.id); - } - } - } */ } } @Override - protected boolean ReadString(Resource res, String[] Props, BiomeConfig biomeConfig) throws NumberFormatException + public void load(List args) throws InvalidResourceException { - if (Props[0].contains(""."")) - { - String[] block = Props[0].split(""\\.""); - res.BlockId = CheckBlock(block[0]); - res.BlockData = CheckValue(block[1], 0, 16); - } else - { - res.BlockId = CheckBlock(Props[0]); - } + assureSize(5, args); + blockId = getBlockId(args.get(0)); + blockData = getBlockData(args.get(0)); + frequency = getInt(args.get(1), 1, 100); + rarity = getInt(args.get(2), 1, 100); + minAltitude = getInt(args.get(3), TerrainControl.worldDepth, TerrainControl.worldHeight); + maxAltitude = getInt(args.get(4), minAltitude + 1, TerrainControl.worldHeight); + } - res.Frequency = CheckValue(Props[1], 1, 100); - res.Rarity = CheckValue(Props[2], 0, 100); - res.MinAltitude = CheckValue(Props[3], 0, biomeConfig.worldConfig.WorldHeight); - res.MaxAltitude = CheckValue(Props[4], 0, biomeConfig.worldConfig.WorldHeight, res.MinAltitude); - return true; + @Override + public ResourceType getType() + { + return ResourceType.biomeConfigResource; } @Override - protected String WriteString(Resource res, String blockSources) + public String makeString() { - String blockId = res.BlockIdToName(res.BlockId); - if (res.BlockData > 0) - { - blockId += ""."" + res.BlockData; - } - return blockId + "","" + res.Frequency + "","" + res.Rarity + "","" + res.MinAltitude + "","" + res.MaxAltitude; + return ""SmallLake("" + makeMaterial(blockId, blockData) + "","" + frequency + "","" + rarity + "","" + minAltitude + "","" + maxAltitude + "")""; } } diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/TreeGen.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/TreeGen.java index 842080d89..c9d1ad663 100644 --- a/common/src/com/khorn/terraincontrol/generator/resourcegens/TreeGen.java +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/TreeGen.java @@ -1,304 +1,90 @@ package com.khorn.terraincontrol.generator.resourcegens; -import com.khorn.terraincontrol.configuration.BiomeConfig; -import com.khorn.terraincontrol.configuration.Resource; -import com.khorn.terraincontrol.LocalWorld; -import com.khorn.terraincontrol.customobjects.BODefaultValues; -import com.khorn.terraincontrol.customobjects.CustomObjectCompiled; -import com.khorn.terraincontrol.customobjects.CustomObjectGen; -import com.khorn.terraincontrol.customobjects.ObjectsStore; - import java.util.ArrayList; -import java.util.HashMap; +import java.util.List; import java.util.Random; -public class TreeGen extends ResourceGenBase -{ - @Override - protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, int z) - { +import com.khorn.terraincontrol.LocalWorld; +import com.khorn.terraincontrol.TerrainControl; +import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.customobjects.CustomObject; +import com.khorn.terraincontrol.exception.InvalidResourceException; - } +public class TreeGen extends Resource +{ + private List trees; + private List treeNames; + private List treeChances; @Override - public void Process(LocalWorld world, Random rand, Resource res, int x, int z) + public void process(LocalWorld world, Random random, int chunkX, int chunkZ) { - for (int i = 0; i < res.Frequency; i++) + for (int i = 0; i < frequency; i++) { - - int _x = x + rand.nextInt(16) + 8; - int _z = z + rand.nextInt(16) + 8; - int _y = world.getHighestBlockYAt(_x, _z); - SpawnTree(world, rand, res, _x, _y, _z); - } - } - - public boolean SpawnTree(LocalWorld world, Random rand, Resource res, int x, int y, int z) - { - boolean treeSpawned = false; - - for (int t = 0; t < res.TreeTypes.length && !treeSpawned; t++) - { - if (rand.nextInt(100) < res.TreeChances[t]) + for (int treeNumber = 0; treeNumber < trees.size(); treeNumber++) { - switch (res.TreeTypes[t]) + if (random.nextInt(100) < treeChances.get(treeNumber)) { - case CustomTree: - CustomObjectCompiled SelectedObject = res.CUObjects[t]; - // TODO Branch check ?!!! - - if (!CustomObjectGen.ObjectCanSpawn(world, x, y, z, SelectedObject)) - continue; - - treeSpawned = CustomObjectGen.GenerateCustomObject(world, rand, x, y, z, SelectedObject); - - if (treeSpawned) - CustomObjectGen.GenerateCustomObjectFromGroup(world, rand, x, y, z, SelectedObject); - break; - case CustomTreeWorld: - treeSpawned = SpawnCustomTreeFromArray(world, rand, x, y, z, res.CUObjectsWorld); - break; - case CustomTreeBiome: - treeSpawned = SpawnCustomTreeFromArray(world, rand, x, y, z, res.CUObjectsBiome); - break; - default: - treeSpawned = world.PlaceTree(res.TreeTypes[t], rand, x, y, z); + int x = chunkX * 16 + random.nextInt(16); + int z = chunkZ * 16 + random.nextInt(16); + if (trees.get(treeNumber).spawnAsTree(world, random, x, z)) + { + // Success, on to the next tree! break; + } } } } - return treeSpawned; - - } - - private boolean SpawnCustomTreeFromArray(LocalWorld world, Random rand, int x, int y, int z, CustomObjectCompiled[] CUObjects) - { - - if (CUObjects.length == 0) - return false; - - boolean objectSpawned = false; - int spawnAttempts = 0; - while (!objectSpawned) - { - if (spawnAttempts > world.getSettings().objectSpawnRatio) - return false; - - spawnAttempts++; - - CustomObjectCompiled SelectedObject = CUObjects[rand.nextInt(CUObjects.length)]; - if (SelectedObject.Branch) - continue; - - if (rand.nextInt(100) < SelectedObject.Rarity) - { - - if (!CustomObjectGen.ObjectCanSpawn(world, x, y, z, SelectedObject)) - continue; - - objectSpawned = CustomObjectGen.GenerateCustomObject(world, rand, x, y, z, SelectedObject); - - if (objectSpawned) - CustomObjectGen.GenerateCustomObjectFromGroup(world, rand, x, y, z, SelectedObject); - } - } - - return objectSpawned; } @Override - protected boolean ReadString(Resource res, String[] Props, BiomeConfig biomeConfig) throws NumberFormatException + public void load(List args) throws InvalidResourceException { - if (res.Type == ResourceType.Sapling) - { - if (Props[0].equals(""All"")) - res.BlockData = -1; - else - res.BlockData = CheckValue(Props[0], 0, 3); - - } else - res.Frequency = CheckValue(Props[0], 1, 100); - - ArrayList treeTypes = new ArrayList(); - ArrayList treeChances = new ArrayList(); - - ArrayList customTrees = new ArrayList(); - HashMap> Groups = new HashMap>(); - - boolean hasCustomTreeWorld = false; - boolean hasCustomTreeBiome = false; - - for (int index = 1; (index + 1) < Props.length; index += 2) - { - String tree = Props[index]; - boolean defaultTreeFound = false; - for (TreeType type : TreeType.values()) - { - if (type == TreeType.CustomTree || type == TreeType.CustomTreeWorld || type == TreeType.CustomTreeBiome) - continue; - - if (type.name().equals(tree)) - { - defaultTreeFound = true; - - treeTypes.add(type); - treeChances.add(CheckValue(Props[index + 1], 0, 100)); - break; - } - } - if (defaultTreeFound) - continue; - - // Check custom objects - - if (tree.equals(BODefaultValues.BO_Use_World.stringValue())) - { - treeTypes.add(TreeType.CustomTreeWorld); - treeChances.add(CheckValue(Props[index + 1], 0, 100)); - hasCustomTreeWorld = true; - continue; - } - - if (tree.equals(BODefaultValues.BO_Use_Biome.stringValue())) - { - treeTypes.add(TreeType.CustomTreeBiome); - treeChances.add(CheckValue(Props[index + 1], 0, 100)); - hasCustomTreeBiome = true; - continue; - } - - CustomObjectCompiled obj = ObjectsStore.CompileString(tree, biomeConfig.worldConfig.CustomObjectsDirectory); - if (obj == null) - obj = ObjectsStore.CompileString(tree, ObjectsStore.GlobalDirectory); - if (obj != null) - { - customTrees.add(obj); - treeTypes.add(TreeType.CustomTree); - treeChances.add(CheckValue(Props[index + 1], 0, 100)); + assureSize(3, args); - if (!obj.GroupId.equals("""")) - { - if (!Groups.containsKey(obj.GroupId)) - Groups.put(obj.GroupId, new ArrayList()); + frequency = getInt(args.get(0), 1, 100); - Groups.get(obj.GroupId).add(obj); - - } - } + trees = new ArrayList(); + treeNames = new ArrayList(); + treeChances = new ArrayList(); - - } - if (treeChances.size() == 0) - return false; - - - if (hasCustomTreeBiome) + for (int i = 1; i < args.size() - 1; i += 2) { - ArrayList customTreesBiome = new ArrayList(); - for (CustomObjectCompiled objectCompiled : biomeConfig.CustomObjectsCompiled) + CustomObject object = TerrainControl.getCustomObjectManager().getObjectFromString(args.get(i), worldConfig); + if (object == null) { - if (!objectCompiled.Tree) - continue; - customTreesBiome.add(objectCompiled); - if (!objectCompiled.GroupId.equals("""")) - { - if (!Groups.containsKey(objectCompiled.GroupId)) - Groups.put(objectCompiled.GroupId, new ArrayList()); - - Groups.get(objectCompiled.GroupId).add(objectCompiled); - - } - + throw new InvalidResourceException(""Custom object "" + args.get(i) + "" not found!""); } - - res.CUObjectsBiome = customTreesBiome.toArray(res.CUObjectsBiome); - - } - - if (hasCustomTreeWorld) - { - ArrayList customTreesWorld = new ArrayList(); - for (CustomObjectCompiled objectCompiled : biomeConfig.worldConfig.CustomObjectsCompiled) + if(!object.canSpawnAsTree()) { - if (objectCompiled.CheckBiome(biomeConfig.Name)) - { - if (!objectCompiled.Tree) - continue; - customTreesWorld.add(objectCompiled); - if (!objectCompiled.GroupId.equals("""")) - { - if (!Groups.containsKey(objectCompiled.GroupId)) - Groups.put(objectCompiled.GroupId, new ArrayList()); - - Groups.get(objectCompiled.GroupId).add(objectCompiled); - - } - } - + throw new InvalidResourceException(""Custom object "" + args.get(i) + "" is not a tree!""); } - - res.CUObjectsWorld = customTreesWorld.toArray(res.CUObjectsBiome); - + trees.add(object); + treeNames.add(args.get(i)); + treeChances.add(getInt(args.get(i + 1), 1, 100)); } + } - for (CustomObjectCompiled objectCompiled : res.CUObjectsBiome) - if (Groups.containsKey(objectCompiled.GroupId)) - objectCompiled.GroupObjects = Groups.get(objectCompiled.GroupId).toArray(objectCompiled.GroupObjects); - - for (CustomObjectCompiled objectCompiled : res.CUObjectsWorld) - if (Groups.containsKey(objectCompiled.GroupId)) - objectCompiled.GroupObjects = Groups.get(objectCompiled.GroupId).toArray(objectCompiled.GroupObjects); - - for (CustomObjectCompiled objectCompiled : customTrees) - if (Groups.containsKey(objectCompiled.GroupId)) - objectCompiled.GroupObjects = Groups.get(objectCompiled.GroupId).toArray(objectCompiled.GroupObjects); - - Groups.clear(); - - - res.TreeTypes = new TreeType[treeChances.size()]; - res.TreeChances = new int[treeChances.size()]; - res.CUObjects = new CustomObjectCompiled[treeChances.size()]; - res.CUObjectsNames = new String[treeChances.size()]; + @Override + public ResourceType getType() + { + return ResourceType.biomeConfigResource; + } - int customIndex = 0; - for (int t = 0; t < treeTypes.size(); t++) + @Override + public String makeString() + { + String output = ""Tree("" + frequency; + for (int i = 0; i < treeNames.size(); i++) { - res.TreeTypes[t] = treeTypes.get(t); - res.TreeChances[t] = treeChances.get(t); - if (treeTypes.get(t) == TreeType.CustomTree) - res.CUObjects[t] = customTrees.get(customIndex++); + output += "","" + treeNames.get(i) + "","" + treeChances.get(i); } - - return true; + return output + "")""; } @Override - protected String WriteString(Resource res, String blockSources) + public void spawn(LocalWorld world, Random random, int x, int z) { - String output; - if (res.Type == ResourceType.Sapling) - { - if (res.BlockData == -1) - output = ""All""; - else - output = """" + res.BlockData; - - } else - output = String.valueOf(res.Frequency); - for (int i = 0; i < res.TreeChances.length; i++) - { - output += "",""; - - if (res.TreeTypes[i] == TreeType.CustomTreeWorld) - output += BODefaultValues.BO_Use_World.stringValue() + "","" + res.TreeChances[i]; - else if (res.TreeTypes[i] == TreeType.CustomTreeBiome) - output += BODefaultValues.BO_Use_Biome.stringValue() + "","" + res.TreeChances[i]; - else if (res.TreeTypes[i] == TreeType.CustomTree) - output += res.CUObjects[i].Name + (res.CUObjects[i].ChangedSettings.equals("""") ? """" : (""("" + res.CUObjects[i].ChangedSettings + "")"")) + "","" + res.TreeChances[i]; - else - output += res.TreeTypes[i].name() + "","" + res.TreeChances[i]; - } - return output; + // Left blank, as process() already handles this } } diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/TreeType.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/TreeType.java index 4cf9d4f78..32271c4de 100644 --- a/common/src/com/khorn/terraincontrol/generator/resourcegens/TreeType.java +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/TreeType.java @@ -2,17 +2,5 @@ public enum TreeType { - Tree, - BigTree, - Forest, - HugeMushroom, - SwampTree, - Taiga1, - Taiga2, - JungleTree, - GroundBush, - CocoaTree, - CustomTree, - CustomTreeWorld, - CustomTreeBiome + Tree, BigTree, Forest, HugeMushroom, SwampTree, Taiga1, Taiga2, JungleTree, GroundBush, CocoaTree, CustomTree, CustomTreeWorld, CustomTreeBiome } \ No newline at end of file diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/UnderWaterOreGen.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/UnderWaterOreGen.java index 02506b868..0a3c2daa2 100644 --- a/common/src/com/khorn/terraincontrol/generator/resourcegens/UnderWaterOreGen.java +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/UnderWaterOreGen.java @@ -1,36 +1,43 @@ package com.khorn.terraincontrol.generator.resourcegens; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + import com.khorn.terraincontrol.LocalWorld; -import com.khorn.terraincontrol.configuration.BiomeConfig; import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.exception.InvalidResourceException; -import java.util.Random; - -public class UnderWaterOreGen extends ResourceGenBase +public class UnderWaterOreGen extends Resource { + private int blockId; + private List sourceBlocks; + private int size; + private int blockData; + @Override - protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, int z) + public void spawn(LocalWorld world, Random rand, int x, int z) { int y = world.getSolidHeight(x, z); if (world.getLiquidHeight(x, z) < y || y == -1) return; - int i = rand.nextInt(res.MaxSize); - int j = 2; - for (int k = x - i; k <= x + i; k++) + int currentSize = rand.nextInt(size); + int two = 2; + for (int k = x - currentSize; k <= x + currentSize; k++) { - for (int m = z - i; m <= z + i; m++) + for (int m = z - currentSize; m <= z + currentSize; m++) { int n = k - x; int i1 = m - z; - if (n * n + i1 * i1 <= i * i) + if (n * n + i1 * i1 <= currentSize * currentSize) { - for (int i2 = y - j; i2 <= y + j; i2++) + for (int i2 = y - two; i2 <= y + two; i2++) { int i3 = world.getTypeId(k, i2, m); - if (res.CheckSourceId(i3)) + if (sourceBlocks.contains(i3)) { - world.setBlock(k, i2, m, res.BlockId, 0, false, false, false); + world.setBlock(k, i2, m, blockId, blockData, false, false, false); } } } @@ -39,25 +46,30 @@ protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, } @Override - protected boolean ReadString(Resource res, String[] Props, BiomeConfig biomeConfig) throws NumberFormatException + public void load(List args) throws InvalidResourceException { + assureSize(5, args); + blockId = getBlockId(args.get(0)); + blockData = getBlockData(args.get(0)); + size = getInt(args.get(1), 1, 8); + frequency = getInt(args.get(2), 1, 100); + rarity = getInt(args.get(3), 1, 100); + sourceBlocks = new ArrayList(); + for (int i = 4; i < args.size(); i++) + { + sourceBlocks.add(getBlockId(args.get(i))); + } + } - res.BlockId = CheckBlock(Props[0]); - res.MaxSize = CheckValue(Props[1], 1, 8); - res.Frequency = CheckValue(Props[2], 1, 100); - res.Rarity = CheckValue(Props[3], 0, 100); - - - res.SourceBlockId = new int[Props.length - 4]; - for (int i = 4; i < Props.length; i++) - res.SourceBlockId[i - 4] = CheckBlock(Props[i]); - - return true; + @Override + public ResourceType getType() + { + return ResourceType.biomeConfigResource; } @Override - protected String WriteString(Resource res, String blockSources) + public String makeString() { - return res.BlockIdToName(res.BlockId) + "","" + res.MaxSize + "","" + res.Frequency + "","" + res.Rarity + blockSources; + return ""UnderWaterOre("" + makeMaterial(blockId, blockData) + "","" + size + "","" + frequency + "","" + rarity + makeMaterial(sourceBlocks) + "")""; } } diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/UndergroundLakeGen.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/UndergroundLakeGen.java index 4ce19ea1d..61b3e417f 100644 --- a/common/src/com/khorn/terraincontrol/generator/resourcegens/UndergroundLakeGen.java +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/UndergroundLakeGen.java @@ -1,23 +1,30 @@ package com.khorn.terraincontrol.generator.resourcegens; -import com.khorn.terraincontrol.configuration.BiomeConfig; import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.exception.InvalidResourceException; import com.khorn.terraincontrol.DefaultMaterial; import com.khorn.terraincontrol.LocalWorld; +import com.khorn.terraincontrol.TerrainControl; import com.khorn.terraincontrol.util.MathHelper; +import java.util.List; import java.util.Random; -public class UndergroundLakeGen extends ResourceGenBase +public class UndergroundLakeGen extends Resource { + private int minSize; + private int maxSize; + private int minAltitude; + private int maxAltitude; + @Override - protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, int z) + public void spawn(LocalWorld world, Random rand, int x, int z) { - int y = rand.nextInt(res.MaxAltitude - res.MinAltitude) + res.MinAltitude; + int y = rand.nextInt(maxAltitude - minAltitude) + minAltitude; if (y >= world.getHighestBlockYAt(x, z)) return; - int size = rand.nextInt(res.MaxSize - res.MinSize) + res.MinSize; + int size = rand.nextInt(maxSize - minSize) + minSize; float mPi = rand.nextFloat() * 3.141593F; @@ -54,29 +61,34 @@ protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, int uBlock = world.getTypeId(xLake, yLake - 1, zLake); if (uBlock != 0) // not air world.setBlock(xLake, yLake, zLake, DefaultMaterial.WATER.id, 0, false, false, false); - else // Air block + else + // Air block world.setBlock(xLake, yLake, zLake, 0, 0, false, false, false); } } } @Override - protected boolean ReadString(Resource res, String[] Props, BiomeConfig biomeConfig) throws NumberFormatException + public void load(List args) throws InvalidResourceException { + assureSize(6, args); + minSize = getInt(args.get(0), 1, 25); + maxSize = getInt(args.get(1), minSize, 60); + frequency = getInt(args.get(2), 1, 100); + rarity = getInt(args.get(3), 1, 100); + minAltitude = getInt(args.get(4), TerrainControl.worldDepth, TerrainControl.worldHeight); + maxAltitude = getInt(args.get(5), minAltitude + 1, TerrainControl.worldHeight); + } - res.MinSize = CheckValue(Props[0], 1, 25); - res.MaxSize = CheckValue(Props[1], 1, 60, res.MinSize); - res.Frequency = CheckValue(Props[2], 1, 100); - res.Rarity = CheckValue(Props[3], 0, 100); - res.MinAltitude = CheckValue(Props[4], 0, biomeConfig.worldConfig.WorldHeight); - res.MaxAltitude = CheckValue(Props[5], 0, biomeConfig.worldConfig.WorldHeight, res.MinAltitude); - - return true; + @Override + public ResourceType getType() + { + return ResourceType.biomeConfigResource; } @Override - protected String WriteString(Resource res, String blockSources) + public String makeString() { - return res.MinSize + "","" + res.MaxSize + "","" + res.Frequency + "","" + res.Rarity + "","" + res.MinAltitude + "","" + res.MaxAltitude; + return ""UnderGroundLake("" + minSize + "","" + maxSize + "","" + frequency + "","" + rarity + "","" + minAltitude + "","" + maxAltitude + "")""; } } diff --git a/common/src/com/khorn/terraincontrol/generator/resourcegens/VinesGen.java b/common/src/com/khorn/terraincontrol/generator/resourcegens/VinesGen.java index d921efc66..73328bc50 100644 --- a/common/src/com/khorn/terraincontrol/generator/resourcegens/VinesGen.java +++ b/common/src/com/khorn/terraincontrol/generator/resourcegens/VinesGen.java @@ -1,22 +1,27 @@ package com.khorn.terraincontrol.generator.resourcegens; -import com.khorn.terraincontrol.configuration.BiomeConfig; -import com.khorn.terraincontrol.configuration.Resource; +import java.util.List; +import java.util.Random; + import com.khorn.terraincontrol.DefaultMaterial; import com.khorn.terraincontrol.LocalWorld; +import com.khorn.terraincontrol.TerrainControl; +import com.khorn.terraincontrol.configuration.Resource; +import com.khorn.terraincontrol.exception.InvalidResourceException; -import java.util.Random; - -public class VinesGen extends ResourceGenBase +public class VinesGen extends Resource { + private int minAltitude; + private int maxAltitude; + @Override - protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, int z) + public void spawn(LocalWorld world, Random rand, int x, int z) { int _x = x; int _z = z; - int y = res.MinAltitude; + int y = minAltitude; - while (y < res.MaxAltitude) + while (y < maxAltitude) { if (world.isEmpty(_x, y, _z)) { @@ -36,51 +41,54 @@ protected void SpawnResource(LocalWorld world, Random rand, Resource res, int x, } - public boolean canPlace(LocalWorld world, int x, int y, int z, int paramInt4) { int id; switch (paramInt4) { - default: - return false; - case 1: - id = (world.getTypeId(x, y + 1, z)); - break; - case 2: - id = (world.getTypeId(x, y, z + 1)); - break; - case 3: - id = (world.getTypeId(x, y, z - 1)); - break; - case 5: - id = (world.getTypeId(x - 1, y, z)); - break; - case 4: - id = (world.getTypeId(x + 1, y, z)); - break; + default: + return false; + case 1: + id = (world.getTypeId(x, y + 1, z)); + break; + case 2: + id = (world.getTypeId(x, y, z + 1)); + break; + case 3: + id = (world.getTypeId(x, y, z - 1)); + break; + case 5: + id = (world.getTypeId(x - 1, y, z)); + break; + case 4: + id = (world.getTypeId(x + 1, y, z)); + break; } return DefaultMaterial.getMaterial(id).isSolid(); } - - public static final int[] d = {-1, -1, 2, 0, 1, 3}; - public static final int[] OPPOSITE_FACING = {1, 0, 3, 2, 5, 4}; + public static final int[] d = { -1, -1, 2, 0, 1, 3 }; + public static final int[] OPPOSITE_FACING = { 1, 0, 3, 2, 5, 4 }; @Override - protected boolean ReadString(Resource res, String[] Props, BiomeConfig biomeConfig) throws NumberFormatException + public void load(List args) throws InvalidResourceException { - res.Frequency = CheckValue(Props[0], 1, 100); - res.Rarity = CheckValue(Props[1], 0, 100); - res.MinAltitude = CheckValue(Props[2], 0, biomeConfig.worldConfig.WorldHeight); - res.MaxAltitude = CheckValue(Props[3], 0, biomeConfig.worldConfig.WorldHeight, res.MinAltitude); + assureSize(4, args); + frequency = getInt(args.get(0), 1, 100); + rarity = getInt(args.get(1), 1, 100); + minAltitude = getInt(args.get(2), TerrainControl.worldDepth, TerrainControl.worldHeight); + maxAltitude = getInt(args.get(3), minAltitude + 1, TerrainControl.worldHeight); + } - return true; + @Override + public ResourceType getType() + { + return ResourceType.biomeConfigResource; } @Override - protected String WriteString(Resource res, String blockSources) + public String makeString() { - return res.Frequency + "","" + res.Rarity + "","" + res.MinAltitude + "","" + res.MaxAltitude; + return ""Vines("" + frequency + "","" + rarity + "","" + minAltitude + "","" + maxAltitude + "")""; } } diff --git a/forge/src/com/khorn/terraincontrol/forge/TCPlugin.java b/forge/src/com/khorn/terraincontrol/forge/TCPlugin.java index 8491df29c..a17b48b74 100644 --- a/forge/src/com/khorn/terraincontrol/forge/TCPlugin.java +++ b/forge/src/com/khorn/terraincontrol/forge/TCPlugin.java @@ -9,7 +9,7 @@ import com.khorn.terraincontrol.TerrainControl; import com.khorn.terraincontrol.TerrainControlEngine; import com.khorn.terraincontrol.configuration.TCDefaultValues; -import com.khorn.terraincontrol.customobjects.ObjectsStore; +import com.khorn.terraincontrol.customobjects.BODefaultValues; import com.khorn.terraincontrol.util.Txt; import cpw.mods.fml.common.FMLCommonHandler; @@ -52,8 +52,6 @@ public void load(FMLInitializationEvent event) TerrainControl.startEngine(this); // Register localization LanguageRegistry.instance().addStringLocalization(""generator.TerrainControl"", ""TerrainControl""); - // Load global custom objects - ObjectsStore.ReadObjects(terrainControlDirectory); // Register world type worldType = new TCWorldType(this, 4, ""TerrainControl""); // Register channel @@ -98,4 +96,10 @@ public void log(Level level, String... messages) System.out.println(""TerrainControl: "" + Txt.implode(messages, "","")); } + @Override + public File getGlobalObjectsDirectory() + { + return new File(terrainControlDirectory, BODefaultValues.BO_GlobalDirectoryName.stringValue()); + } + }" 8ee465103850a3dca018273fe5952e40d5c45a66,spring-framework,Improve StringUtils.cleanPath--Issue: SPR-11793-,c,https://github.com/spring-projects/spring-framework,"diff --git a/spring-core/src/main/java/org/springframework/util/StringUtils.java b/spring-core/src/main/java/org/springframework/util/StringUtils.java index 126cab69fcd3..b659486a19d0 100644 --- a/spring-core/src/main/java/org/springframework/util/StringUtils.java +++ b/spring-core/src/main/java/org/springframework/util/StringUtils.java @@ -622,7 +622,12 @@ public static String cleanPath(String path) { String prefix = """"; if (prefixIndex != -1) { prefix = pathToUse.substring(0, prefixIndex + 1); - pathToUse = pathToUse.substring(prefixIndex + 1); + if (prefix.contains(""/"")) { + prefix = """"; + } + else { + pathToUse = pathToUse.substring(prefixIndex + 1); + } } if (pathToUse.startsWith(FOLDER_SEPARATOR)) { prefix = prefix + FOLDER_SEPARATOR; diff --git a/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java b/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java index b366ed7f96d0..c362a92ed529 100644 --- a/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java @@ -299,6 +299,8 @@ public void testCleanPath() { assertEquals(""../mypath/myfile"", StringUtils.cleanPath(""../mypath/../mypath/myfile"")); assertEquals(""../mypath/myfile"", StringUtils.cleanPath(""mypath/../../mypath/myfile"")); assertEquals(""/../mypath/myfile"", StringUtils.cleanPath(""/../mypath/myfile"")); + assertEquals(""/mypath/myfile"", StringUtils.cleanPath(""/a/:b/../../mypath/myfile"")); + assertEquals(""file:///c:/path/to/the%20file.txt"", StringUtils.cleanPath(""file:///c:/some/../path/to/the%20file.txt"")); } public void testPathEquals() {" 5a273e85d77f50d49612ab7ad05b6a8b049c4bae,brandonborkholder$glg2d,"Well, realized that the fragment shader can't composite or blend. So I think this is the closest I'll get to a decent implementation of the Duff-Porter blend functionality.",p,https://github.com/brandonborkholder/glg2d,"diff --git a/src/joglg2d/JOGLG2D.java b/src/joglg2d/JOGLG2D.java index a5479fde..ceadf90b 100644 --- a/src/joglg2d/JOGLG2D.java +++ b/src/joglg2d/JOGLG2D.java @@ -221,52 +221,41 @@ public Composite getComposite() { public void setComposite(Composite comp) { if (comp instanceof AlphaComposite) { switch (((AlphaComposite) comp).getRule()) { - case AlphaComposite.CLEAR: - gl.glBlendFunc(GL.GL_ZERO, GL.GL_ZERO); - break; - + /* + * Since the destination _always_ covers the entire canvas (i.e. there + * are always color components for every pixel), some of these + * composites can be collapsed into each other. They matter when Java2D + * is drawing into an image and the destination may not take up the + * entire canvas. + */ case AlphaComposite.SRC: - gl.glBlendFunc(GL.GL_ONE, GL.GL_ZERO); + case AlphaComposite.SRC_IN: + gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ZERO); break; case AlphaComposite.SRC_OVER: - gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA); - break; - - case AlphaComposite.SRC_IN: - gl.glBlendFunc(GL.GL_DST_ALPHA, GL.GL_ZERO); + case AlphaComposite.SRC_ATOP: + gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); break; case AlphaComposite.SRC_OUT: - gl.glBlendFunc(GL.GL_ONE_MINUS_DST_ALPHA, GL.GL_ZERO); - break; - - case AlphaComposite.SRC_ATOP: - gl.glBlendFunc(GL.GL_DST_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); + case AlphaComposite.CLEAR: + gl.glBlendFunc(GL.GL_ZERO, GL.GL_ZERO); break; case AlphaComposite.DST: - gl.glBlendFunc(GL.GL_ZERO, GL.GL_ONE); - break; - case AlphaComposite.DST_OVER: - gl.glBlendFunc(GL.GL_ONE_MINUS_DST_ALPHA, GL.GL_ONE); + gl.glBlendFunc(GL.GL_ZERO, GL.GL_ONE); break; case AlphaComposite.DST_IN: + case AlphaComposite.DST_ATOP: gl.glBlendFunc(GL.GL_ZERO, GL.GL_SRC_ALPHA); break; case AlphaComposite.DST_OUT: - gl.glBlendFunc(GL.GL_ZERO, GL.GL_ONE_MINUS_SRC_ALPHA); - break; - - case AlphaComposite.DST_ATOP: - gl.glBlendFunc(GL.GL_ONE_MINUS_DST_ALPHA, GL.GL_SRC_ALPHA); - break; - case AlphaComposite.XOR: - gl.glBlendFunc(GL.GL_ONE_MINUS_DST_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); + gl.glBlendFunc(GL.GL_ZERO, GL.GL_ONE_MINUS_SRC_ALPHA); break; } @@ -587,10 +576,9 @@ public void fillRect(int x, int y, int width, int height) { @Override public void clearRect(int x, int y, int width, int height) { - Color origColor = color; - setColor(background); + setColor(gl, background); fillRect(x, y, width, height); - setColor(origColor); + setColor(gl, color); } @Override diff --git a/test/joglg2d/VisualTest.java b/test/joglg2d/VisualTest.java index 6b704dc4..59fecb75 100644 --- a/test/joglg2d/VisualTest.java +++ b/test/joglg2d/VisualTest.java @@ -396,7 +396,7 @@ public void paint(Graphics2D g2d) { } @Test - public void srcOverRuleTest() throws Exception { + public void compositeTest() throws Exception { tester.setPainter(new Painter() { @Override public void paint(Graphics2D g2d) { @@ -434,7 +434,6 @@ void draw(Graphics2D g2d, AlphaComposite composite, String name) { dest.lineTo(100, 0); dest.lineTo(100, 100); dest.closePath(); - g2d.setColor(g2d.getBackground()); g2d.setComposite(AlphaComposite.SrcOver); g2d.setColor(new Color(255, 0, 0, 190)); g2d.fill(dest);" b07575194155e5f90e3ab514812d11dd74eef75f,abashev$vfs-s3,"Added support for Server Side Encryption - Added S3FileSystemConfigBuilder - Refactored S3FileSystem + Object so that FileSystem encapsulates the various options (similar to SftpFileSystem+Object) - Added get/setServerSideEncryption as necessary - Added integration tests - Fixed a bug in copy file tests where file counts were not being tested properly. ",a,https://github.com/abashev/vfs-s3,"diff --git a/src/main/java/com/intridea/io/vfs/provider/s3/S3FileObject.java b/src/main/java/com/intridea/io/vfs/provider/s3/S3FileObject.java index 683a6dde..96572709 100644 --- a/src/main/java/com/intridea/io/vfs/provider/s3/S3FileObject.java +++ b/src/main/java/com/intridea/io/vfs/provider/s3/S3FileObject.java @@ -47,18 +47,8 @@ public class S3FileObject extends AbstractFileObject { private static final String MIMETYPE_JETS3T_DIRECTORY = ""application/x-directory""; - /** Amazon S3 service */ - private final AWSCredentials awsCredentials; - private final AmazonS3 service; - - private final TransferManager transferManager; - - /** Amazon S3 bucket */ - private final Bucket bucket; - /** Amazon S3 object */ private ObjectMetadata objectMetadata; - private String objectKey; /** @@ -82,16 +72,9 @@ public class S3FileObject extends AbstractFileObject { */ private Owner fileOwner; - public S3FileObject( - AbstractFileName fileName, S3FileSystem fileSystem, AWSCredentials awsCredentials, AmazonS3 service, - TransferManager transferManager, Bucket bucket - ) throws FileSystemException { + public S3FileObject(AbstractFileName fileName, + S3FileSystem fileSystem) throws FileSystemException { super(fileName, fileSystem); - - this.awsCredentials = awsCredentials; - this.service = service; - this.bucket = bucket; - this.transferManager = transferManager; } @Override @@ -100,7 +83,7 @@ protected void doAttach() { try { // Do we have file with name? String candidateKey = getS3Key(); - objectMetadata = service.getObjectMetadata(bucket.getName(), candidateKey); + objectMetadata = getService().getObjectMetadata(getBucket().getName(), candidateKey); objectKey = candidateKey; logger.info(""Attach file to S3 Object: "" + objectKey); @@ -116,7 +99,7 @@ protected void doAttach() { try { // Do we have folder with that name? String candidateKey = getS3Key() + FileName.SEPARATOR; - objectMetadata = service.getObjectMetadata(bucket.getName(), candidateKey); + objectMetadata = getService().getObjectMetadata(getBucket().getName(), candidateKey); objectKey = candidateKey; logger.info(""Attach folder to S3 Object: "" + objectKey); @@ -156,7 +139,7 @@ protected void doDetach() throws Exception { @Override protected void doDelete() throws Exception { - service.deleteObject(bucket.getName(), objectKey); + getService().deleteObject(getBucket().getName(), objectKey); } @Override @@ -164,7 +147,7 @@ protected void doCreateFolder() throws Exception { if (logger.isDebugEnabled()) { logger.debug( ""Create new folder in bucket ["" + - ((bucket != null) ? bucket.getName() : ""null"") + + ((getBucket() != null) ? getBucket().getName() : ""null"") + ""] with key ["" + ((objectMetadata != null) ? objectKey : ""null"") + ""]"" @@ -178,7 +161,9 @@ protected void doCreateFolder() throws Exception { InputStream input = new ByteArrayInputStream(new byte[0]); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(0); - service.putObject(new PutObjectRequest(bucket.getName(), objectKey + FileName.SEPARATOR, input, metadata)); + if (((S3FileSystem)getFileSystem()).getServerSideEncryption()) + metadata.setServerSideEncryption(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); + getService().putObject(new PutObjectRequest(getBucket().getName(), objectKey + FileName.SEPARATOR, input, metadata)); } @Override @@ -228,13 +213,13 @@ protected String[] doListChildren() throws Exception { path = path + ""/""; } - ObjectListing listing = service.listObjects(bucket.getName(), path); + ObjectListing listing = getService().listObjects(getBucket().getName(), path); final List summaries = new ArrayList(listing.getObjectSummaries()); while (listing.isTruncated()) { final ListObjectsRequest loReq = new ListObjectsRequest(); - loReq.setBucketName(bucket.getName()); + loReq.setBucketName(getBucket().getName()); loReq.setMarker(listing.getNextMarker()); - listing = service.listObjects(loReq); + listing = getService().listObjects(loReq); summaries.addAll(listing.getObjectSummaries()); } @@ -275,13 +260,13 @@ protected FileObject[] doListChildrenResolved() throws Exception path = path + ""/""; } - ObjectListing listing = service.listObjects(bucket.getName(), path); + ObjectListing listing = getService().listObjects(getBucket().getName(), path); final List summaries = new ArrayList(listing.getObjectSummaries()); while (listing.isTruncated()) { final ListObjectsRequest loReq = new ListObjectsRequest(); - loReq.setBucketName(bucket.getName()); + loReq.setBucketName(getBucket().getName()); loReq.setMarker(listing.getNextMarker()); - listing = service.listObjects(loReq); + listing = getService().listObjects(loReq); summaries.addAll(listing.getObjectSummaries()); } @@ -332,7 +317,7 @@ private void downloadOnce () throws FileSystemException { final String failedMessage = ""Failed to download S3 Object %s. %s""; final String objectPath = getName().getPath(); try { - S3Object obj = service.getObject(bucket.getName(), objectKey); + S3Object obj = getService().getObject(getBucket().getName(), objectKey); logger.info(String.format(""Downloading S3 Object: %s"", objectPath)); InputStream is = obj.getObjectContent(); if (obj.getObjectMetadata().getContentLength() > 0) { @@ -438,7 +423,7 @@ private Owner getS3Owner() { */ private AccessControlList getS3Acl() { String key = getS3Key(); - return """".equals(key) ? service.getBucketAcl(bucket.getName()) : service.getObjectAcl(bucket.getName(), key); + return """".equals(key) ? getService().getBucketAcl(getBucket().getName()) : getService().getObjectAcl(getBucket().getName(), key); } /** @@ -450,12 +435,12 @@ private void putS3Acl (AccessControlList s3Acl) { String key = getS3Key(); // Determine context. Object or Bucket if ("""".equals(key)) { - service.setBucketAcl(bucket.getName(), s3Acl); + getService().setBucketAcl(getBucket().getName(), s3Acl); } else { // Before any operations with object it must be attached doAttach(); // Put ACL to S3 - service.setObjectAcl(bucket.getName(), objectKey, s3Acl); + getService().setObjectAcl(getBucket().getName(), objectKey, s3Acl); } } @@ -608,7 +593,7 @@ public void setAcl (Acl acl) throws FileSystemException { * @return */ public String getHttpUrl() { - StringBuilder sb = new StringBuilder(""http://"" + bucket.getName() + "".s3.amazonaws.com/""); + StringBuilder sb = new StringBuilder(""http://"" + getBucket().getName() + "".s3.amazonaws.com/""); String key = getS3Key(); // Determine context. Object or Bucket @@ -627,9 +612,9 @@ public String getHttpUrl() { public String getPrivateUrl() { return String.format( ""s3://%s:%s@%s/%s"", - awsCredentials.getAWSAccessKeyId(), - awsCredentials.getAWSSecretKey(), - bucket.getName(), + getAwsCredentials().getAWSAccessKeyId(), + getAwsCredentials().getAWSSecretKey(), + getBucket().getName(), getS3Key() ); } @@ -646,7 +631,9 @@ public String getSignedUrl(int expireInSeconds) throws FileSystemException { cal.add(SECOND, expireInSeconds); try { - return service.generatePresignedUrl(bucket.getName(), getS3Key(), cal.getTime()).toString(); + return getService().generatePresignedUrl( + getBucket().getName(), + getS3Key(), cal.getTime()).toString(); } catch (AmazonServiceException e) { throw new FileSystemException(e); } @@ -658,19 +645,40 @@ public String getSignedUrl(int expireInSeconds) throws FileSystemException { * @throws FileSystemException */ public String getMD5Hash() throws FileSystemException { - final String key = getS3Key(); String hash = null; + ObjectMetadata metadata = getObjectMetadata(); + if (metadata != null) { + hash = metadata.getETag(); // TODO this is something different than mentioned in methodname / javadoc + } + + return hash; + } + + public ObjectMetadata getObjectMetadata() throws FileSystemException { try { - ObjectMetadata metadata = service.getObjectMetadata(bucket.getName(), key); - if (metadata != null) { - hash = metadata.getETag(); // TODO this is something different than mentioned in methodname / javadoc - } + return getService().getObjectMetadata(getBucket().getName(), getS3Key()); } catch (AmazonServiceException e) { throw new FileSystemException(e); } + } - return hash; + /** FileSystem object containing configuration */ + protected AWSCredentials getAwsCredentials() { + return ((S3FileSystem)getFileSystem()).getAwsCredentials(); + } + + protected AmazonS3 getService() { + return ((S3FileSystem)getFileSystem()).getService(); + } + + protected TransferManager getTransferManager() { + return ((S3FileSystem)getFileSystem()).getTransferManager(); + } + + /** Amazon S3 bucket */ + protected Bucket getBucket() { + return ((S3FileSystem)getFileSystem()).getBucket(); } /** @@ -689,11 +697,15 @@ protected void onClose() throws IOException { FileChannel cacheFileChannel = getCacheFileChannel(); objectMetadata.setContentLength(cacheFileChannel.size()); - objectMetadata.setContentType(Mimetypes.getInstance().getMimetype(getName().getBaseName())); - + objectMetadata.setContentType( + Mimetypes.getInstance().getMimetype(getName().getBaseName())); + if (((S3FileSystem)getFileSystem()).getServerSideEncryption()) + objectMetadata.setServerSideEncryption( + ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); try { - final Upload upload = transferManager.upload( - bucket.getName(), objectKey, newInputStream(cacheFileChannel), objectMetadata + final Upload upload = getTransferManager().upload( + getBucket().getName(), objectKey, + newInputStream(cacheFileChannel), objectMetadata ); upload.addProgressListener(new ProgressListener() { @@ -708,7 +720,7 @@ public void progressChanged(ProgressEvent progressEvent) { if ((progress - lastValue) > REPORT_THRESHOLD) { logger.info( ""File "" + objectKey + - "" was uploaded to "" + bucket.getName() + + "" was uploaded to "" + getBucket().getName() + "" for "" + (int) progress + ""%"" ); @@ -716,7 +728,7 @@ public void progressChanged(ProgressEvent progressEvent) { } if (progressEvent.getEventCode() == COMPLETED_EVENT_CODE) { - logger.info(""File "" + objectKey + "" was successfully uploaded to "" + bucket.getName()); + logger.info(""File "" + objectKey + "" was successfully uploaded to "" + getBucket().getName()); } } }); @@ -790,21 +802,23 @@ public void copyFrom(final FileObject file, final FileSelector selector) // Copy across try { + String srcBucketName = ((S3FileObject)srcFile).getBucket().getName(); + String srcFileName = ((S3FileObject)srcFile).getS3Key(); + String destBucketName = ((S3FileObject)destFile).getBucket().getName(); + String destFileName = ((S3FileObject)destFile).getS3Key(); if (srcFile.getType() == FileType.FOLDER) { - service.copyObject( - ((S3FileObject)srcFile).bucket.getName(), - ((S3FileObject)srcFile).getS3Key() + FileName.SEPARATOR, - ((S3FileObject)destFile).bucket.getName(), - ((S3FileObject)destFile).getS3Key() + FileName.SEPARATOR - ); - } else { - service.copyObject( - ((S3FileObject)srcFile).bucket.getName(), - ((S3FileObject)srcFile).getS3Key(), - ((S3FileObject)destFile).bucket.getName(), - ((S3FileObject)destFile).getS3Key() - ); - } + srcFileName = srcFileName + FileName.SEPARATOR; + destFileName = destFileName + FileName.SEPARATOR; + } + CopyObjectRequest copy = new CopyObjectRequest( + srcBucketName, srcFileName, destBucketName, destFileName); + if (srcFile.getType() == FileType.FILE + && ((S3FileSystem)destFile.getFileSystem()).getServerSideEncryption()) { + ObjectMetadata meta = ((S3FileObject)srcFile).getObjectMetadata(); + meta.setServerSideEncryption(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); + copy.setNewObjectMetadata(meta); + } + getService().copyObject(copy); destFile.close(); } catch (AmazonServiceException e) { diff --git a/src/main/java/com/intridea/io/vfs/provider/s3/S3FileSystem.java b/src/main/java/com/intridea/io/vfs/provider/s3/S3FileSystem.java index b2653f7a..74dd428a 100644 --- a/src/main/java/com/intridea/io/vfs/provider/s3/S3FileSystem.java +++ b/src/main/java/com/intridea/io/vfs/provider/s3/S3FileSystem.java @@ -33,15 +33,19 @@ public class S3FileSystem extends AbstractFileSystem { private final Bucket bucket; private final TransferManager transferManager; + private Boolean serverSideEncryption; + public S3FileSystem( - S3FileName fileName, AWSCredentials awsCredentials, AmazonS3 service, FileSystemOptions fileSystemOptions - ) throws FileSystemException { + S3FileName fileName, AWSCredentials awsCredentials, AmazonS3 service, + FileSystemOptions fileSystemOptions) throws FileSystemException { super(fileName, null, fileSystemOptions); String bucketId = fileName.getBucketId(); this.awsCredentials = awsCredentials; this.service = service; + this.serverSideEncryption = S3FileSystemConfigBuilder.getInstance() + .getServerSideEncryption(fileSystemOptions); try { if (service.doesBucketExist(bucketId)) { @@ -71,8 +75,32 @@ protected void addCapabilities(Collection caps) { caps.addAll(S3FileProvider.capabilities); } + public Boolean getServerSideEncryption() { + return serverSideEncryption; + } + + public void setServerSideEncryption(Boolean serverSideEncryption) { + this.serverSideEncryption = serverSideEncryption; + } + + protected Bucket getBucket() { + return bucket; + } + + protected AWSCredentials getAwsCredentials() { + return awsCredentials; + } + + protected AmazonS3 getService() { + return service; + } + + protected TransferManager getTransferManager() { + return transferManager; + } + @Override protected FileObject createFile(AbstractFileName fileName) throws Exception { - return new S3FileObject(fileName, this, awsCredentials, service, transferManager, bucket); + return new S3FileObject(fileName, this); } } diff --git a/src/main/java/com/intridea/io/vfs/provider/s3/S3FileSystemConfigBuilder.java b/src/main/java/com/intridea/io/vfs/provider/s3/S3FileSystemConfigBuilder.java new file mode 100644 index 00000000..15de92fd --- /dev/null +++ b/src/main/java/com/intridea/io/vfs/provider/s3/S3FileSystemConfigBuilder.java @@ -0,0 +1,47 @@ +package com.intridea.io.vfs.provider.s3; + +import org.apache.commons.vfs2.FileSystem; +import org.apache.commons.vfs2.FileSystemConfigBuilder; +import org.apache.commons.vfs2.FileSystemOptions; + +public class S3FileSystemConfigBuilder extends FileSystemConfigBuilder { + private static final S3FileSystemConfigBuilder BUILDER = new S3FileSystemConfigBuilder(); + + private static final String SERVER_SIDE_ENCRYPTION = S3FileSystemConfigBuilder.class.getName() + "".SERVER_SIDE_ENCRYPTION""; + + private S3FileSystemConfigBuilder() + { + super(""s3.""); + } + + public static S3FileSystemConfigBuilder getInstance() + { + return BUILDER; + } + + @Override + protected Class getConfigClass() { + return S3FileSystem.class; + } + + /** + * use server-side encryption. + * + * @param opts The FileSystemOptions. + * @param serverSideEncryption true if server-side encryption should be used. + */ + public void setServerSideEncryption(FileSystemOptions opts, boolean serverSideEncryption) + { + setParam(opts, SERVER_SIDE_ENCRYPTION, serverSideEncryption ? Boolean.TRUE : Boolean.FALSE); + } + + /** + * @param opts The FileSystemOptions. + * @return true if server-side encryption is being used. + * @see #setServerSideEncryption(org.apache.commons.vfs2.FileSystemOptions, boolean) + */ + public Boolean getServerSideEncryption(FileSystemOptions opts) + { + return getBoolean(opts, SERVER_SIDE_ENCRYPTION, false); + } +} diff --git a/src/test/java/com/intridea/io/vfs/provider/s3/S3ProviderTest.java b/src/test/java/com/intridea/io/vfs/provider/s3/S3ProviderTest.java index d60c3eab..ca911083 100644 --- a/src/test/java/com/intridea/io/vfs/provider/s3/S3ProviderTest.java +++ b/src/test/java/com/intridea/io/vfs/provider/s3/S3ProviderTest.java @@ -1,5 +1,6 @@ package com.intridea.io.vfs.provider.s3; +import com.amazonaws.services.s3.model.ObjectMetadata; import com.intridea.io.vfs.TestEnvironment; import com.intridea.io.vfs.operations.IMD5HashGetter; import com.intridea.io.vfs.operations.IPublicUrlsGetter; @@ -14,6 +15,7 @@ import java.io.FileNotFoundException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.Arrays; import java.util.Locale; import java.util.Properties; import java.util.Random; @@ -29,8 +31,7 @@ public class S3ProviderTest { private static final String BACKUP_ZIP = ""src/test/resources/backup.zip""; private FileSystemManager fsManager; - - private String fileName, dirName, bucketName, bigFile; + private String fileName, encryptedFileName, dirName, bucketName, bigFile; private FileObject file, dir; private FileSystemOptions opts; @@ -41,6 +42,7 @@ public void setUp() throws FileNotFoundException, IOException { fsManager = VFS.getManager(); Random r = new Random(); + encryptedFileName = ""vfs-encrypted-file"" + r.nextInt(1000); fileName = ""vfs-file"" + r.nextInt(1000); dirName = ""vfs-dir"" + r.nextInt(1000); bucketName = config.getProperty(""s3.testBucket"", ""vfs-s3-tests""); @@ -54,6 +56,17 @@ public void createFileOk() throws FileSystemException { assertTrue(file.exists()); } + @Test + public void createEncryptedFileOk() throws FileSystemException { + file = fsManager.resolveFile(""s3://"" + bucketName + ""/test-place/"" + encryptedFileName, opts); + ((S3FileSystem)file.getFileSystem()).setServerSideEncryption(true); + file.createFile(); + assertTrue(file.exists()); + assertEquals( + ((S3FileObject) file).getObjectMetadata().getServerSideEncryption(), + ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); + } + @Test(expectedExceptions={FileSystemException.class}) public void createFileFailed() throws FileSystemException { FileObject tmpFile = fsManager.resolveFile(""s3://../new-mpoint/vfs-bad-file""); @@ -130,6 +143,31 @@ public void upload() throws FileNotFoundException, IOException { dest.copyFrom(src, Selectors.SELECT_SELF); assertTrue(dest.exists() && dest.getType().equals(FileType.FILE)); + assertEquals(((S3FileObject)dest).getObjectMetadata().getServerSideEncryption(), + null); + } + + @Test(dependsOnMethods = {""createEncryptedFileOk""}) + public void uploadEncrypted() throws FileNotFoundException, IOException { + FileObject dest = fsManager.resolveFile(""s3://"" + bucketName + ""/test-place/backup.zip""); + ((S3FileSystem)dest.getFileSystem()).setServerSideEncryption(true); + + // Delete file if exists + if (dest.exists()) { + dest.delete(); + } + + // Copy data + final File backupFile = new File(BACKUP_ZIP); + + assertTrue(backupFile.exists(), ""Backup file should exists""); + + FileObject src = fsManager.resolveFile(backupFile.getAbsolutePath()); + dest.copyFrom(src, Selectors.SELECT_SELF); + + assertTrue(dest.exists() && dest.getType().equals(FileType.FILE)); + assertEquals(((S3FileObject)dest).getObjectMetadata().getServerSideEncryption(), + ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); } @Test(dependsOnMethods={""createFileOk""}) @@ -318,7 +356,9 @@ public void getUrls() throws FileSystemException { final String signedUrl = urlsGetter.getSignedUrl(60); - assertTrue(signedUrl.startsWith(""https://"" + bucketName + "".s3.amazonaws.com/test-place%2Fbackup.zip?"")); + assertTrue( + signedUrl.startsWith(""https://s3.amazonaws.com/"" + bucketName + ""/test-place%2Fbackup.zip?""), + signedUrl); assertTrue(signedUrl.indexOf(""Signature="") != (-1)); assertTrue(signedUrl.indexOf(""Expires="") != (-1)); assertTrue(signedUrl.indexOf(""AWSAccessKeyId="") != (-1)); @@ -347,16 +387,40 @@ public void getMD5Hash() throws NoSuchAlgorithmException, FileNotFoundException, @Test(dependsOnMethods={""findFiles""}) public void copyInsideBucket() throws FileSystemException { - FileObject testsDir = fsManager.resolveFile(dir, ""find-tests""); - FileObject testsDirCopy = testsDir.getParent().resolveFile(""find-tests-copy""); - testsDirCopy.copyFrom(testsDir, Selectors.SELECT_SELF_AND_CHILDREN); - - // Should have same number of files - FileObject[] files = testsDir.findFiles(Selectors.SELECT_ALL); - FileObject[] filesCopy = testsDir.findFiles(Selectors.SELECT_ALL); - assertEquals(files.length, filesCopy.length); + FileObject testsDir = fsManager.resolveFile(dir, ""find-tests""); + FileObject testsDirCopy = testsDir.getParent().resolveFile(""find-tests-copy""); + testsDirCopy.copyFrom(testsDir, Selectors.SELECT_SELF_AND_CHILDREN); + + // Should have same number of files + FileObject[] files = testsDir.findFiles(Selectors.SELECT_SELF_AND_CHILDREN); + FileObject[] filesCopy = testsDirCopy.findFiles(Selectors.SELECT_SELF_AND_CHILDREN); + assertEquals(files.length, filesCopy.length, + Arrays.deepToString(files) + "" vs. "" + Arrays.deepToString(filesCopy)); } + @Test(dependsOnMethods={""findFiles""}) + public void copyAllToEncryptedInsideBucket() throws FileSystemException { + FileObject testsDir = fsManager.resolveFile(dir, ""find-tests""); + FileObject testsDirCopy = testsDir.getParent().resolveFile(""find-tests-encrypted-copy""); + ((S3FileSystem)testsDirCopy.getFileSystem()).setServerSideEncryption(true); + + testsDirCopy.copyFrom(testsDir, Selectors.SELECT_ALL); + + // Should have same number of files + FileObject[] files = testsDir.findFiles(Selectors.SELECT_ALL); + FileObject[] filesCopy = testsDirCopy.findFiles(Selectors.SELECT_ALL); + assertEquals(files.length, filesCopy.length); + + for (int i = 0; i < files.length; i++) { + if (files[i].getType() == FileType.FILE) { + assertEquals(((S3FileObject)files[i]).getObjectMetadata().getServerSideEncryption(), + null); + assertEquals(((S3FileObject)filesCopy[i]).getObjectMetadata().getServerSideEncryption(), + ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); + } + } + } + @Test(dependsOnMethods={""findFiles"", ""download""}) public void delete() throws FileSystemException { FileObject testsDir = fsManager.resolveFile(dir, ""find-tests"");" 4ae79b6666c22898decaee37c3e33e209ff23b30,d3scomp$jdeeco,Remove old MATSimSimulation and move the functionality into the plugin,p,https://github.com/d3scomp/jdeeco,"diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimSimulation.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimSimulation.java deleted file mode 100644 index 7da955166..000000000 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimSimulation.java +++ /dev/null @@ -1,213 +0,0 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; - -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import org.matsim.api.core.v01.TransportMode; -import org.matsim.core.controler.Controler; -import org.matsim.core.controler.events.StartupEvent; -import org.matsim.core.controler.listener.StartupListener; -import org.matsim.core.mobsim.framework.Mobsim; -import org.matsim.core.router.util.TravelTime; -import org.matsim.withinday.trafficmonitoring.TravelTimeCollector; -import org.matsim.withinday.trafficmonitoring.TravelTimeCollectorFactory; - -import cz.cuni.mff.d3s.deeco.logging.Log; -import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.Simulation; - -public class MATSimSimulation extends Simulation implements MATSimSimulationStepListener { - - private static final String SIMULATION_CALLBACK = ""SIMULATION_CALLBACK""; - - private long currentMilliseconds; - private final long simulationStep; // in milliseconds - private final TravelTime travelTime; - private final TreeSet callbacks; - private final Map hostIdToCallback; - private final Controler controler; - private final JDEECoWithinDayMobsimListener listener; - private final MATSimDataProvider matSimProvider; - private final MATSimDataReceiver matSimReceiver; - private final Map hosts; - private final MATSimExtractor extractor; - - public MATSimSimulation(MATSimDataReceiver matSimReceiver, MATSimDataProvider matSimProvider, - MATSimUpdater updater, MATSimExtractor extractor, - final Collection agentSources, String matSimConf) { - this.callbacks = new TreeSet<>(); - this.hostIdToCallback = new HashMap<>(); - this.hosts = new HashMap<>(); - - this.controler = new MATSimPreloadingControler(matSimConf); - this.controler.setOverwriteFiles(true); - this.controler.getConfig().getQSimConfigGroup().setSimStarttimeInterpretation(""onlyUseStarttime""); - - double end = this.controler.getConfig().getQSimConfigGroup().getEndTime(); - double start = this.controler.getConfig().getQSimConfigGroup().getStartTime(); - double step = this.controler.getConfig().getQSimConfigGroup().getTimeStepSize(); - Log.i(""Starting simulation: matsimStartTime: "" + start + "" matsimEndTime: "" + end); - this.extractor = extractor; - this.listener = new JDEECoWithinDayMobsimListener(this, updater, extractor); - this.matSimProvider = matSimProvider; - this.matSimReceiver = matSimReceiver; - - Set analyzedModes = new HashSet(); - analyzedModes.add(TransportMode.car); - travelTime = new TravelTimeCollectorFactory().createTravelTimeCollector(controler.getScenario(), analyzedModes); - - controler.addControlerListener(new StartupListener() { - public void notifyStartup(StartupEvent event) { - controler.getEvents().addHandler((TravelTimeCollector) travelTime); - controler.getMobsimListeners().add((TravelTimeCollector) travelTime); - controler.setMobsimFactory(new JDEECoMobsimFactory(listener, agentSources)); - } - }); - /** - * Bind MATSim listener with the agent source. It is necessary to let the listener know about the jDEECo agents - * that it needs to update with data coming from a jDEECo runtime. - */ - for (AdditionAwareAgentSource source : agentSources) { - if (source instanceof JDEECoAgentSource) { - listener.registerAgentProvider((JDEECoAgentSource) source); - } - } - - this.simulationStep = secondsToMilliseconds(step); - currentMilliseconds = secondsToMilliseconds(controler.getConfig().getQSimConfigGroup().getStartTime()); - } - - public void addHost(String id, cz.cuni.mff.d3s.jdeeco.matsim.MATSimSimulation.Host host) { - hosts.put(id, host); - } - - public cz.cuni.mff.d3s.jdeeco.matsim.MATSimSimulation.Host getHost(String id) { - return hosts.get(id); - } - - public Controler getControler() { - return this.controler; - } - - public TravelTime getTravelTime() { - return this.travelTime; - } - - @Override - public long getCurrentMilliseconds() { - return currentMilliseconds; - } - - @Override - public synchronized void callAt(long absoluteTime, String hostId) { - Callback callback = hostIdToCallback.remove(hostId); - if (callback != null) { - callbacks.remove(callback); - } - callback = new Callback(hostId, absoluteTime); - hostIdToCallback.put(hostId, callback); - // System.out.println(""For "" + absoluteTime); - callbacks.add(callback); - } - - @Override - public void at(double seconds, Mobsim mobsim) { - // Exchange data with MATSim - long milliseconds = secondsToMilliseconds(seconds); - matSimReceiver.setMATSimData(extractor.extractFromMATSim(listener.getAllJDEECoAgents(), mobsim)); - listener.updateJDEECoAgents(matSimProvider.getMATSimData()); - // Add callback for the MATSim step - callAt(milliseconds + simulationStep, SIMULATION_CALLBACK); - cz.cuni.mff.d3s.jdeeco.matsim.MATSimSimulation.Host host; - Callback callback; - // Iterate through all the callbacks until the MATSim callback. - while (!callbacks.isEmpty()) { - callback = callbacks.pollFirst(); - if (callback.getHostId().equals(SIMULATION_CALLBACK)) { - break; - } - currentMilliseconds = callback.getAbsoluteTime(); - // System.out.println(""At: "" + currentMilliseconds); - host = (cz.cuni.mff.d3s.jdeeco.matsim.MATSimSimulation.Host) hosts.get(callback.hostId); - host.at(millisecondsToSeconds(currentMilliseconds)); - } - } - - public synchronized void run() { - controler.run(); - } - - private class Callback implements Comparable { - - private final long milliseconds; - private final String hostId; - - public Callback(String hostId, long milliseconds) { - this.hostId = hostId; - this.milliseconds = milliseconds; - } - - public long getAbsoluteTime() { - return milliseconds; - } - - public String getHostId() { - return hostId; - } - - @Override - public int compareTo(Callback c) { - if (c.getAbsoluteTime() < milliseconds) { - return 1; - } else if (c.getAbsoluteTime() > milliseconds) { - return -1; - } else if (this == c) { - return 0; - } else { - return this.hashCode() < c.hashCode() ? 1 : -1; - } - } - - public String toString() { - return hostId + "" "" + milliseconds; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + getOuterType().hashCode(); - result = prime * result + ((hostId == null) ? 0 : hostId.hashCode()); - result = prime * result + (int) (milliseconds ^ (milliseconds >>> 32)); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Callback other = (Callback) obj; - if (!getOuterType().equals(other.getOuterType())) - return false; - if (hostId == null) { - if (other.hostId != null) - return false; - } else if (!hostId.equals(other.hostId)) - return false; - if (milliseconds != other.milliseconds) - return false; - return true; - } - - private MATSimSimulation getOuterType() { - return MATSimSimulation.this; - } - } -} diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/package-info.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/package-info.java deleted file mode 100644 index 7b4598c6b..000000000 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Ported sources from jDEECo 2 - */ -package cz.cuni.mff.d3s.deeco.simulation.matsim; \ No newline at end of file diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/MATSimSimulation.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/MATSimSimulation.java index 270690016..7476b88cd 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/MATSimSimulation.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/MATSimSimulation.java @@ -3,54 +3,122 @@ import java.io.File; import java.io.IOException; import java.util.Arrays; +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.TreeSet; import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.TransportMode; import org.matsim.core.basic.v01.IdImpl; import org.matsim.core.controler.Controler; +import org.matsim.core.controler.events.StartupEvent; +import org.matsim.core.controler.listener.StartupListener; +import org.matsim.core.mobsim.framework.Mobsim; +import org.matsim.core.router.util.TravelTime; +import org.matsim.withinday.trafficmonitoring.TravelTimeCollector; +import org.matsim.withinday.trafficmonitoring.TravelTimeCollectorFactory; +import cz.cuni.mff.d3s.deeco.logging.Log; import cz.cuni.mff.d3s.deeco.network.AbstractHost; import cz.cuni.mff.d3s.deeco.runtime.DEECoContainer; import cz.cuni.mff.d3s.deeco.runtime.DEECoPlugin; -import cz.cuni.mff.d3s.deeco.simulation.matsim.AdditionAwareAgentSource; -import cz.cuni.mff.d3s.deeco.simulation.matsim.DefaultMATSimExtractor; -import cz.cuni.mff.d3s.deeco.simulation.matsim.DefaultMATSimUpdater; -import cz.cuni.mff.d3s.deeco.simulation.matsim.JDEECoAgent; -import cz.cuni.mff.d3s.deeco.simulation.matsim.JDEECoAgentSource; -import cz.cuni.mff.d3s.deeco.simulation.matsim.MATSimRouter; import cz.cuni.mff.d3s.deeco.timer.CurrentTimeProvider; import cz.cuni.mff.d3s.deeco.timer.SimulationTimer; import cz.cuni.mff.d3s.deeco.timer.TimerEventListener; import cz.cuni.mff.d3s.jdeeco.matsim.old.roadtrains.MATSimDataProviderReceiver; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.AdditionAwareAgentSource; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.DefaultMATSimExtractor; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.DefaultMATSimUpdater; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.JDEECoAgent; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.JDEECoAgentSource; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.JDEECoMobsimFactory; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.JDEECoWithinDayMobsimListener; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.MATSimDataProvider; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.MATSimDataReceiver; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.MATSimExtractor; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.MATSimPreloadingControler; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.MATSimRouter; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.MATSimSimulationStepListener; /** * Plug-in providing MATSim simulation * + * Based on the code from the jDEECo 2 simulation project + * * @author Vladimir Matena * */ public class MATSimSimulation implements DEECoPlugin { - class TimerProvider implements SimulationTimer { + private final TreeSet callbacks; + + class TimerProvider implements SimulationTimer, CurrentTimeProvider /* + * TODO: Current time provider or simulation + * timer + */, MATSimSimulationStepListener { @Override public void notifyAt(long time, TimerEventListener listener, DEECoContainer node) { // System.out.println(""NOTIFY AT CALLED FOR: "" + time + "" NODE:"" + node.getId()); - MATSimSimulation.this.oldSimulation.callAt(time, String.valueOf(node.getId())); - oldSimulation.getHost(String.valueOf(node.getId())).listener = listener; + // MATSimSimulation.this.oldSimulation.callAt(time, String.valueOf(node.getId())); + final String hostId = String.valueOf(node.getId()); + + callAt(time, hostId); + + MATSimSimulation.this.getHost(String.valueOf(node.getId())).listener = listener; + } + + public synchronized void callAt(long absoluteTime, String hostId) { + Callback callback = hostIdToCallback.remove(hostId); + if (callback != null) { + callbacks.remove(callback); + } + callback = new Callback(hostId, absoluteTime); + hostIdToCallback.put(hostId, callback); + // System.out.println(""For "" + absoluteTime); + callbacks.add(callback); } @Override public long getCurrentMilliseconds() { - return MATSimSimulation.this.oldSimulation.getCurrentMilliseconds(); + return MATSimSimulation.this.currentMilliseconds; } @Override public void start(long duration) { - double startTime = MATSimSimulation.this.oldSimulation.getControler().getConfig().getQSimConfigGroup() - .getStartTime(); + double startTime = MATSimSimulation.this.getController().getConfig().getQSimConfigGroup().getStartTime(); double endTime = startTime + (((double) (duration)) / 1000); - MATSimSimulation.this.oldSimulation.getControler().getConfig().getQSimConfigGroup().setEndTime(endTime); - MATSimSimulation.this.oldSimulation.run(); + MATSimSimulation.this.getController().getConfig().getQSimConfigGroup().setEndTime(endTime); + MATSimSimulation.this.getController().run(); + } + + @Override + public void at(double seconds, Mobsim mobsim) { + // Exchange data with MATSim + long milliseconds = secondsToMilliseconds(seconds); + matSimReceiver.setMATSimData(extractor.extractFromMATSim(listener.getAllJDEECoAgents(), mobsim)); + listener.updateJDEECoAgents(matSimProvider.getMATSimData()); + // Add callback for the MATSim step + callAt(milliseconds + simulationStep, SIMULATION_CALLBACK); + Host host; + Callback callback; + // Iterate through all the callbacks until the MATSim callback. + while (!callbacks.isEmpty()) { + callback = callbacks.pollFirst(); + if (callback.getHostId().equals(SIMULATION_CALLBACK)) { + break; + } + currentMilliseconds = callback.getAbsoluteTime(); + // System.out.println(""At: "" + currentMilliseconds); + host = hosts.get(callback.hostId); + host.at(millisecondsToSeconds(currentMilliseconds)); + } + } + + private double millisecondsToSeconds(long milliseconds) { + return ((double) (milliseconds)) / 1000; } } @@ -69,23 +137,165 @@ public void at(double absoluteTime) { } + private class Callback implements Comparable { + + private final long milliseconds; + private final String hostId; + + public Callback(String hostId, long milliseconds) { + this.hostId = hostId; + this.milliseconds = milliseconds; + } + + public long getAbsoluteTime() { + return milliseconds; + } + + public String getHostId() { + return hostId; + } + + @Override + public int compareTo(Callback c) { + if (c.getAbsoluteTime() < milliseconds) { + return 1; + } else if (c.getAbsoluteTime() > milliseconds) { + return -1; + } else if (this == c) { + return 0; + } else { + return this.hashCode() < c.hashCode() ? 1 : -1; + } + } + + public String toString() { + return hostId + "" "" + milliseconds; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + getOuterType().hashCode(); + result = prime * result + ((hostId == null) ? 0 : hostId.hashCode()); + result = prime * result + (int) (milliseconds ^ (milliseconds >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Callback other = (Callback) obj; + if (!getOuterType().equals(other.getOuterType())) + return false; + if (hostId == null) { + if (other.hostId != null) + return false; + } else if (!hostId.equals(other.hostId)) + return false; + if (milliseconds != other.milliseconds) + return false; + return true; + } + + private MATSimSimulation getOuterType() { + return MATSimSimulation.this; + } + } + private final TimerProvider timer = new TimerProvider(); - private final cz.cuni.mff.d3s.deeco.simulation.matsim.MATSimSimulation oldSimulation; private final JDEECoAgentSource agentSource = new JDEECoAgentSource(); private final MATSimRouter router; private final MATSimDataProviderReceiver matSimProviderReceiver = new MATSimDataProviderReceiver( new LinkedList()); + // private final cz.cuni.mff.d3s.deeco.simulation.matsim.MATSimSimulation oldSimulation; + + private static final String SIMULATION_CALLBACK = ""SIMULATION_CALLBACK""; + private long currentMilliseconds; + private final long simulationStep; // in milliseconds + private final TravelTime travelTime; + private final Map hostIdToCallback; + private final Controler controler; + private final JDEECoWithinDayMobsimListener listener; + private final MATSimDataProvider matSimProvider; + private final MATSimDataReceiver matSimReceiver; + private final Map hosts; + private final MATSimExtractor extractor; + + // private final Exchanger exchanger; + public MATSimSimulation(File config, AdditionAwareAgentSource... additionalAgentSources) throws IOException { List agentSources = new LinkedList<>(); agentSources.add(agentSource); agentSources.addAll(Arrays.asList(additionalAgentSources)); - oldSimulation = new cz.cuni.mff.d3s.deeco.simulation.matsim.MATSimSimulation(matSimProviderReceiver, - matSimProviderReceiver, new DefaultMATSimUpdater(), new DefaultMATSimExtractor(), agentSources, - config.getAbsolutePath()); + /* + * oldSimulation = new cz.cuni.mff.d3s.deeco.simulation.matsim.MATSimSimulation(matSimProviderReceiver, + * matSimProviderReceiver, new DefaultMATSimUpdater(), new DefaultMATSimExtractor(), agentSources, + * config.getAbsolutePath()); + */ + // this.exchanger = new Exchanger(); + + this.callbacks = new TreeSet<>(); + this.hostIdToCallback = new HashMap<>(); + this.hosts = new HashMap<>(); + + this.controler = new MATSimPreloadingControler(config.getAbsolutePath()); + this.controler.setOverwriteFiles(true); + this.controler.getConfig().getQSimConfigGroup().setSimStarttimeInterpretation(""onlyUseStarttime""); - router = new MATSimRouter(oldSimulation.getControler(), oldSimulation.getTravelTime(), 10 /* TODO: FAKE VALUE */); + double end = this.controler.getConfig().getQSimConfigGroup().getEndTime(); + double start = this.controler.getConfig().getQSimConfigGroup().getStartTime(); + double step = this.controler.getConfig().getQSimConfigGroup().getTimeStepSize(); + Log.i(""Starting simulation: matsimStartTime: "" + start + "" matsimEndTime: "" + end); + this.extractor = new DefaultMATSimExtractor(); + this.listener = new JDEECoWithinDayMobsimListener(timer, new DefaultMATSimUpdater(), extractor); + this.matSimProvider = (MATSimDataProvider) matSimProviderReceiver; + this.matSimReceiver = (MATSimDataReceiver) matSimProviderReceiver; + + Set analyzedModes = new HashSet(); + analyzedModes.add(TransportMode.car); + travelTime = new TravelTimeCollectorFactory().createTravelTimeCollector(controler.getScenario(), analyzedModes); + + controler.addControlerListener(new StartupListener() { + public void notifyStartup(StartupEvent event) { + controler.getEvents().addHandler((TravelTimeCollector) travelTime); + controler.getMobsimListeners().add((TravelTimeCollector) travelTime); + controler.setMobsimFactory(new JDEECoMobsimFactory(listener, agentSources)); + } + }); + /** + * Bind MATSim listener with the agent source. It is necessary to let the listener know about the jDEECo agents + * that it needs to update with data coming from a jDEECo runtime. + */ + for (AdditionAwareAgentSource source : agentSources) { + if (source instanceof JDEECoAgentSource) { + listener.registerAgentProvider((JDEECoAgentSource) source); + } + } + + this.simulationStep = secondsToMilliseconds(step); + currentMilliseconds = secondsToMilliseconds(controler.getConfig().getQSimConfigGroup().getStartTime()); + + router = new MATSimRouter(getController(), travelTime, 10 /* TODO: FAKE VALUE */); + } + + private long secondsToMilliseconds(double seconds) { + return (long) (seconds * 1000); + } + + public void addHost(String id, cz.cuni.mff.d3s.jdeeco.matsim.MATSimSimulation.Host host) { + hosts.put(id, host); + } + + public Host getHost(String id) { + return hosts.get(id); } public SimulationTimer getTimer() { @@ -95,9 +305,9 @@ public SimulationTimer getTimer() { public MATSimRouter getRouter() { return router; } - + public Controler getController() { - return oldSimulation.getControler(); + return controler; } public MATSimDataProviderReceiver getMATSimProviderReceiver() { @@ -116,8 +326,8 @@ public List> getDependencies() { @Override public void init(DEECoContainer container) { - Host host = new Host(String.valueOf(container.getId()), oldSimulation); + Host host = new Host(String.valueOf(container.getId()), getTimer()); - oldSimulation.addHost(String.valueOf(container.getId()), host); + addHost(String.valueOf(container.getId()), host); } } diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/roadtrains/MATSimDataProviderReceiver.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/roadtrains/MATSimDataProviderReceiver.java index 205cbe3b7..c7047fde2 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/roadtrains/MATSimDataProviderReceiver.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/roadtrains/MATSimDataProviderReceiver.java @@ -8,10 +8,11 @@ import org.matsim.api.core.v01.Id; import org.matsim.core.basic.v01.IdImpl; -import cz.cuni.mff.d3s.deeco.simulation.matsim.MATSimDataProvider; -import cz.cuni.mff.d3s.deeco.simulation.matsim.MATSimDataReceiver; -import cz.cuni.mff.d3s.deeco.simulation.matsim.MATSimInput; -import cz.cuni.mff.d3s.deeco.simulation.matsim.MATSimOutput; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.MATSimDataProvider; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.MATSimDataReceiver; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.MATSimInput; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.MATSimOutput; + public class MATSimDataProviderReceiver implements MATSimDataReceiver, MATSimDataProvider { diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/AdditionAwareAgentSource.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/AdditionAwareAgentSource.java similarity index 90% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/AdditionAwareAgentSource.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/AdditionAwareAgentSource.java index 9dcd57c46..f5e1086a5 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/AdditionAwareAgentSource.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/AdditionAwareAgentSource.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import org.matsim.core.mobsim.framework.AgentSource; import org.matsim.core.mobsim.qsim.QSim; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/DefaultMATSimExtractor.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/DefaultMATSimExtractor.java similarity index 91% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/DefaultMATSimExtractor.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/DefaultMATSimExtractor.java index 6f38f5bff..c12919b95 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/DefaultMATSimExtractor.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/DefaultMATSimExtractor.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import java.util.Collection; import java.util.HashMap; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/DefaultMATSimUpdater.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/DefaultMATSimUpdater.java similarity index 91% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/DefaultMATSimUpdater.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/DefaultMATSimUpdater.java index a82f18c09..bbfb9844b 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/DefaultMATSimUpdater.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/DefaultMATSimUpdater.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import java.util.Collection; import java.util.Map; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/JDEECoAgent.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/JDEECoAgent.java similarity index 99% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/JDEECoAgent.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/JDEECoAgent.java index 6daade023..c5875fb3f 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/JDEECoAgent.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/JDEECoAgent.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import java.util.LinkedList; import java.util.List; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/JDEECoAgentProvider.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/JDEECoAgentProvider.java similarity index 84% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/JDEECoAgentProvider.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/JDEECoAgentProvider.java index bc64756ac..ca3f768da 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/JDEECoAgentProvider.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/JDEECoAgentProvider.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import java.util.Collection; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/JDEECoAgentSource.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/JDEECoAgentSource.java similarity index 96% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/JDEECoAgentSource.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/JDEECoAgentSource.java index 5b18954af..f21290b8c 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/JDEECoAgentSource.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/JDEECoAgentSource.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import java.util.Collection; import java.util.LinkedList; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/JDEECoMobsimFactory.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/JDEECoMobsimFactory.java similarity index 97% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/JDEECoMobsimFactory.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/JDEECoMobsimFactory.java index a1c03bd98..2ca34fbb9 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/JDEECoMobsimFactory.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/JDEECoMobsimFactory.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import java.util.Collection; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/JDEECoWithinDayMobsimListener.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/JDEECoWithinDayMobsimListener.java similarity index 98% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/JDEECoWithinDayMobsimListener.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/JDEECoWithinDayMobsimListener.java index c5cf1e25b..0f3f0cffb 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/JDEECoWithinDayMobsimListener.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/JDEECoWithinDayMobsimListener.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import java.util.Collection; import java.util.LinkedList; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimDataProvider.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimDataProvider.java similarity index 83% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimDataProvider.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimDataProvider.java index 2f0479567..cdf574239 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimDataProvider.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimDataProvider.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import java.util.Map; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimDataReceiver.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimDataReceiver.java similarity index 80% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimDataReceiver.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimDataReceiver.java index c8485854e..0536552fc 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimDataReceiver.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimDataReceiver.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; /** diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimExtractor.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimExtractor.java similarity index 78% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimExtractor.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimExtractor.java index ab6a9828d..8aa7b655d 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimExtractor.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimExtractor.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import java.util.Collection; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimInput.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimInput.java similarity index 91% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimInput.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimInput.java index e8c21f89f..d3f3f1b8e 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimInput.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimInput.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import java.util.LinkedList; import java.util.List; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimOMNetCoordinatesTranslator.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimOMNetCoordinatesTranslator.java similarity index 96% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimOMNetCoordinatesTranslator.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimOMNetCoordinatesTranslator.java index cc7664c2b..a3059ae5c 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimOMNetCoordinatesTranslator.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimOMNetCoordinatesTranslator.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.network.Network; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimOutput.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimOutput.java similarity index 88% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimOutput.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimOutput.java index bbdc67ae5..db4169079 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimOutput.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimOutput.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import java.util.List; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimPopulationAgentSource.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimPopulationAgentSource.java similarity index 98% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimPopulationAgentSource.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimPopulationAgentSource.java index 2f0bca14d..a79186398 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimPopulationAgentSource.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimPopulationAgentSource.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import java.util.Collection; import java.util.HashMap; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimPreloadingControler.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimPreloadingControler.java similarity index 93% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimPreloadingControler.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimPreloadingControler.java index c01dcfcd5..00be66f28 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimPreloadingControler.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimPreloadingControler.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import org.matsim.core.controler.Controler; import org.matsim.core.scenario.ScenarioImpl; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimRouter.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimRouter.java similarity index 99% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimRouter.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimRouter.java index 2cee0d5e3..d49692255 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimRouter.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimRouter.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import java.util.Collection; import java.util.LinkedList; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimSimulationStepListener.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimSimulationStepListener.java similarity index 73% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimSimulationStepListener.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimSimulationStepListener.java index c00c4412b..076df9048 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimSimulationStepListener.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimSimulationStepListener.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import org.matsim.core.mobsim.framework.Mobsim; diff --git a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimUpdater.java b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimUpdater.java similarity index 72% rename from jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimUpdater.java rename to jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimUpdater.java index 5c63f650e..7ace9385c 100644 --- a/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/deeco/simulation/matsim/MATSimUpdater.java +++ b/jdeeco-matsim-plugin/src/cz/cuni/mff/d3s/jdeeco/matsim/old/simulation/MATSimUpdater.java @@ -1,4 +1,4 @@ -package cz.cuni.mff.d3s.deeco.simulation.matsim; +package cz.cuni.mff.d3s.jdeeco.matsim.old.simulation; import java.util.Collection; diff --git a/jdeeco-matsim-plugin/test/cz/cuni/mff/d3s/jdeeco/matsim/demo/convoy/Vehicle.java b/jdeeco-matsim-plugin/test/cz/cuni/mff/d3s/jdeeco/matsim/demo/convoy/Vehicle.java index 7d6bada36..400c20e51 100644 --- a/jdeeco-matsim-plugin/test/cz/cuni/mff/d3s/jdeeco/matsim/demo/convoy/Vehicle.java +++ b/jdeeco-matsim-plugin/test/cz/cuni/mff/d3s/jdeeco/matsim/demo/convoy/Vehicle.java @@ -13,7 +13,6 @@ import cz.cuni.mff.d3s.deeco.annotations.PeriodicScheduling; import cz.cuni.mff.d3s.deeco.annotations.Process; import cz.cuni.mff.d3s.deeco.logging.Log; -import cz.cuni.mff.d3s.deeco.simulation.matsim.MATSimRouter; import cz.cuni.mff.d3s.deeco.task.ParamHolder; import cz.cuni.mff.d3s.deeco.timer.CurrentTimeProvider; import cz.cuni.mff.d3s.jdeeco.matsim.MATSimVehicle; @@ -21,6 +20,7 @@ import cz.cuni.mff.d3s.jdeeco.matsim.old.roadtrains.ActuatorType; import cz.cuni.mff.d3s.jdeeco.matsim.old.roadtrains.Sensor; import cz.cuni.mff.d3s.jdeeco.matsim.old.roadtrains.SensorType; +import cz.cuni.mff.d3s.jdeeco.matsim.old.simulation.MATSimRouter; @Component public class Vehicle {" 6d7a01a1ea85e77f7f323604ea7ba104dc0944f3,ning$compress,"Overload of factory methods and constructors in Encoders and Streams, to allow specifying a concrete BufferRecycler instance, as an alternative to the default ThreadLocal soft-references policy. The change does not break compatibility with existing API, but adds flexibility for resource-eficiency if used from pools (different threads could reuse the same BufferRecycler instances, avoiding the creation of instances on a per Thread basis) and some minor performance gain in preexistent LZFOutputStream constructors (because ThreadLocal is only accessed once).",p,https://github.com/ning/compress,"diff --git a/src/main/java/com/ning/compress/gzip/GZIPUncompressor.java b/src/main/java/com/ning/compress/gzip/GZIPUncompressor.java index 7f357a4..0338522 100644 --- a/src/main/java/com/ning/compress/gzip/GZIPUncompressor.java +++ b/src/main/java/com/ning/compress/gzip/GZIPUncompressor.java @@ -171,17 +171,22 @@ public class GZIPUncompressor extends Uncompressor public GZIPUncompressor(DataHandler h) { - this(h, DEFAULT_CHUNK_SIZE); + this(h, DEFAULT_CHUNK_SIZE, BufferRecycler.instance(), GZIPRecycler.instance()); } public GZIPUncompressor(DataHandler h, int inputChunkLength) + { + this(h, inputChunkLength, BufferRecycler.instance(), GZIPRecycler.instance()); + } + + public GZIPUncompressor(DataHandler h, int inputChunkLength, BufferRecycler bufferRecycler, GZIPRecycler gzipRecycler) { _inputChunkLength = inputChunkLength; _handler = h; - _recycler = BufferRecycler.instance(); - _decodeBuffer = _recycler.allocDecodeBuffer(DECODE_BUFFER_SIZE); - _gzipRecycler = GZIPRecycler.instance(); - _inflater = _gzipRecycler.allocInflater(); + _recycler = bufferRecycler; + _decodeBuffer = bufferRecycler.allocDecodeBuffer(DECODE_BUFFER_SIZE); + _gzipRecycler = gzipRecycler; + _inflater = gzipRecycler.allocInflater(); _crc = new CRC32(); } diff --git a/src/main/java/com/ning/compress/gzip/OptimizedGZIPInputStream.java b/src/main/java/com/ning/compress/gzip/OptimizedGZIPInputStream.java index 80024dd..bec84e3 100644 --- a/src/main/java/com/ning/compress/gzip/OptimizedGZIPInputStream.java +++ b/src/main/java/com/ning/compress/gzip/OptimizedGZIPInputStream.java @@ -77,15 +77,20 @@ enum State { */ public OptimizedGZIPInputStream(InputStream in) throws IOException + { + this(in, BufferRecycler.instance(), GZIPRecycler.instance()); + } + + public OptimizedGZIPInputStream(InputStream in, BufferRecycler bufferRecycler, GZIPRecycler gzipRecycler) throws IOException { super(); - _bufferRecycler = BufferRecycler.instance(); - _gzipRecycler = GZIPRecycler.instance(); + _bufferRecycler = bufferRecycler; + _gzipRecycler = gzipRecycler; _rawInput = in; - _buffer = _bufferRecycler.allocInputBuffer(INPUT_BUFFER_SIZE); + _buffer = bufferRecycler.allocInputBuffer(INPUT_BUFFER_SIZE); _bufferPtr = _bufferEnd = 0; - _inflater = _gzipRecycler.allocInflater(); + _inflater = gzipRecycler.allocInflater(); _crc = new CRC32(); // And then need to process header... diff --git a/src/main/java/com/ning/compress/lzf/ChunkEncoder.java b/src/main/java/com/ning/compress/lzf/ChunkEncoder.java index 799864d..6c5df0a 100644 --- a/src/main/java/com/ning/compress/lzf/ChunkEncoder.java +++ b/src/main/java/com/ning/compress/lzf/ChunkEncoder.java @@ -75,34 +75,56 @@ public abstract class ChunkEncoder protected byte[] _headerBuffer; /** + * Uses a ThreadLocal soft-referenced BufferRecycler instance. + * * @param totalLength Total encoded length; used for calculating size * of hash table to use */ protected ChunkEncoder(int totalLength) + { + this(totalLength, BufferRecycler.instance()); + } + + /** + * @param totalLength Total encoded length; used for calculating size + * of hash table to use + * @param bufferRecycler Buffer recycler instance, for usages where the + * caller manages the recycler instances + */ + protected ChunkEncoder(int totalLength, BufferRecycler bufferRecycler) { // Need room for at most a single full chunk int largestChunkLen = Math.min(totalLength, LZFChunk.MAX_CHUNK_LEN); int suggestedHashLen = calcHashLen(largestChunkLen); - _recycler = BufferRecycler.instance(); - _hashTable = _recycler.allocEncodingHash(suggestedHashLen); + _recycler = bufferRecycler; + _hashTable = bufferRecycler.allocEncodingHash(suggestedHashLen); _hashModulo = _hashTable.length - 1; // Ok, then, what's the worst case output buffer length? // length indicator for each 32 literals, so: // 21-Feb-2013, tatu: Plus we want to prepend chunk header in place: int bufferLen = largestChunkLen + ((largestChunkLen + 31) >> 5) + LZFChunk.MAX_HEADER_LEN; - _encodeBuffer = _recycler.allocEncodingBuffer(bufferLen); + _encodeBuffer = bufferRecycler.allocEncodingBuffer(bufferLen); } - + /** * Alternate constructor used when we want to avoid allocation encoding * buffer, in cases where caller wants full control over allocations. */ protected ChunkEncoder(int totalLength, boolean bogus) + { + this(totalLength, BufferRecycler.instance(), bogus); + } + + /** + * Alternate constructor used when we want to avoid allocation encoding + * buffer, in cases where caller wants full control over allocations. + */ + protected ChunkEncoder(int totalLength, BufferRecycler bufferRecycler, boolean bogus) { int largestChunkLen = Math.max(totalLength, LZFChunk.MAX_CHUNK_LEN); int suggestedHashLen = calcHashLen(largestChunkLen); - _recycler = BufferRecycler.instance(); - _hashTable = _recycler.allocEncodingHash(suggestedHashLen); + _recycler = bufferRecycler; + _hashTable = bufferRecycler.allocEncodingHash(suggestedHashLen); _hashModulo = _hashTable.length - 1; _encodeBuffer = null; } @@ -297,6 +319,10 @@ public boolean encodeAndWriteChunkIfCompresses(byte[] data, int offset, int inpu return false; } + public BufferRecycler getBufferRecycler() { + return _recycler; + } + /* /////////////////////////////////////////////////////////////////////// // Abstract methods for sub-classes diff --git a/src/main/java/com/ning/compress/lzf/LZFCompressingInputStream.java b/src/main/java/com/ning/compress/lzf/LZFCompressingInputStream.java index 6c49924..e46b8b2 100644 --- a/src/main/java/com/ning/compress/lzf/LZFCompressingInputStream.java +++ b/src/main/java/com/ning/compress/lzf/LZFCompressingInputStream.java @@ -76,16 +76,24 @@ public class LZFCompressingInputStream extends InputStream public LZFCompressingInputStream(InputStream in) { - this(null, in); + this(null, in, BufferRecycler.instance()); } public LZFCompressingInputStream(final ChunkEncoder encoder, InputStream in) + { + this(encoder, in, null); + } + + public LZFCompressingInputStream(final ChunkEncoder encoder, InputStream in, BufferRecycler bufferRecycler) { // may be passed by caller, or could be null _encoder = encoder; _inputStream = in; - _recycler = BufferRecycler.instance(); - _inputBuffer = _recycler.allocInputBuffer(LZFChunk.MAX_CHUNK_LEN); + if (bufferRecycler==null) { + bufferRecycler = (encoder!=null) ? _encoder._recycler : BufferRecycler.instance(); + } + _recycler = bufferRecycler; + _inputBuffer = bufferRecycler.allocInputBuffer(LZFChunk.MAX_CHUNK_LEN); // let's not yet allocate encoding buffer; don't know optimal size } @@ -259,7 +267,7 @@ protected boolean readyBuffer() throws IOException if (_encoder == null) { // need 7 byte header, plus regular max buffer size: int bufferLen = chunkLength + ((chunkLength + 31) >> 5) + 7; - _encoder = ChunkEncoderFactory.optimalNonAllocatingInstance(bufferLen); + _encoder = ChunkEncoderFactory.optimalNonAllocatingInstance(bufferLen, _recycler); } if (_encodedBytes == null) { int bufferLen = chunkLength + ((chunkLength + 31) >> 5) + 7; diff --git a/src/main/java/com/ning/compress/lzf/LZFEncoder.java b/src/main/java/com/ning/compress/lzf/LZFEncoder.java index b147071..9835e2d 100644 --- a/src/main/java/com/ning/compress/lzf/LZFEncoder.java +++ b/src/main/java/com/ning/compress/lzf/LZFEncoder.java @@ -11,6 +11,7 @@ package com.ning.compress.lzf; +import com.ning.compress.BufferRecycler; import com.ning.compress.lzf.util.ChunkEncoderFactory; /** @@ -121,6 +122,36 @@ public static byte[] safeEncode(byte[] data, int offset, int length) return result; } + /** + * Method for compressing given input data using LZF encoding and + * block structure (compatible with lzf command line utility). + * Result consists of a sequence of chunks. + *

+ * Note that {@link ChunkEncoder} instance used is one produced by + * {@link ChunkEncoderFactory#optimalInstance}, which typically + * is ""unsafe"" instance if one can be used on current JVM. + */ + public static byte[] encode(byte[] data, int offset, int length, BufferRecycler bufferRecycler) + { + ChunkEncoder enc = ChunkEncoderFactory.optimalInstance(length, bufferRecycler); + byte[] result = encode(enc, data, offset, length); + enc.close(); // important for buffer reuse! + return result; + } + + /** + * Method that will use ""safe"" {@link ChunkEncoder}, as produced by + * {@link ChunkEncoderFactory#safeInstance}, for encoding. Safe here + * means that it does not use any non-compliant features beyond core JDK. + */ + public static byte[] safeEncode(byte[] data, int offset, int length, BufferRecycler bufferRecycler) + { + ChunkEncoder enc = ChunkEncoderFactory.safeInstance(length, bufferRecycler); + byte[] result = encode(enc, data, offset, length); + enc.close(); + return result; + } + /** * Compression method that uses specified {@link ChunkEncoder} for actual * encoding. @@ -207,6 +238,36 @@ public static int safeAppendEncoded(byte[] input, int inputPtr, int inputLength, /** * Alternate version that accepts pre-allocated output buffer. + *

+ * Note that {@link ChunkEncoder} instance used is one produced by + * {@link ChunkEncoderFactory#optimalNonAllocatingInstance}, which typically + * is ""unsafe"" instance if one can be used on current JVM. + */ + public static int appendEncoded(byte[] input, int inputPtr, int inputLength, + byte[] outputBuffer, int outputPtr, BufferRecycler bufferRecycler) { + ChunkEncoder enc = ChunkEncoderFactory.optimalNonAllocatingInstance(inputLength, bufferRecycler); + int len = appendEncoded(enc, input, inputPtr, inputLength, outputBuffer, outputPtr); + enc.close(); + return len; + } + + /** + * Alternate version that accepts pre-allocated output buffer. + *

+ * Method that will use ""safe"" {@link ChunkEncoder}, as produced by + * {@link ChunkEncoderFactory#safeInstance}, for encoding. Safe here + * means that it does not use any non-compliant features beyond core JDK. + */ + public static int safeAppendEncoded(byte[] input, int inputPtr, int inputLength, + byte[] outputBuffer, int outputPtr, BufferRecycler bufferRecycler) { + ChunkEncoder enc = ChunkEncoderFactory.safeNonAllocatingInstance(inputLength, bufferRecycler); + int len = appendEncoded(enc, input, inputPtr, inputLength, outputBuffer, outputPtr); + enc.close(); + return len; + } + + /** + * Alternate version that accepts pre-allocated output buffer. */ public static int appendEncoded(ChunkEncoder enc, byte[] input, int inputPtr, int inputLength, byte[] outputBuffer, int outputPtr) diff --git a/src/main/java/com/ning/compress/lzf/LZFInputStream.java b/src/main/java/com/ning/compress/lzf/LZFInputStream.java index cd0c280..6626089 100644 --- a/src/main/java/com/ning/compress/lzf/LZFInputStream.java +++ b/src/main/java/com/ning/compress/lzf/LZFInputStream.java @@ -83,7 +83,7 @@ public LZFInputStream(final InputStream inputStream) throws IOException public LZFInputStream(final ChunkDecoder decoder, final InputStream in) throws IOException { - this(decoder, in, false); + this(decoder, in, BufferRecycler.instance(), false); } /** @@ -94,21 +94,45 @@ public LZFInputStream(final ChunkDecoder decoder, final InputStream in) */ public LZFInputStream(final InputStream in, boolean fullReads) throws IOException { - this(ChunkDecoderFactory.optimalInstance(), in, fullReads); + this(ChunkDecoderFactory.optimalInstance(), in, BufferRecycler.instance(), fullReads); } public LZFInputStream(final ChunkDecoder decoder, final InputStream in, boolean fullReads) throws IOException + { + this(decoder, in, BufferRecycler.instance(), fullReads); + } + + public LZFInputStream(final InputStream inputStream, final BufferRecycler bufferRecycler) throws IOException + { + this(inputStream, bufferRecycler, false); + } + + /** + * @param in Underlying input stream to use + * @param fullReads Whether {@link #read(byte[])} should try to read exactly + * as many bytes as requested (true); or just however many happen to be + * available (false) + * @param bufferRecycler Buffer recycler instance, for usages where the + * caller manages the recycler instances + */ + public LZFInputStream(final InputStream in, final BufferRecycler bufferRecycler, boolean fullReads) throws IOException + { + this(ChunkDecoderFactory.optimalInstance(), in, bufferRecycler, fullReads); + } + + public LZFInputStream(final ChunkDecoder decoder, final InputStream in, final BufferRecycler bufferRecycler, boolean fullReads) + throws IOException { super(); _decoder = decoder; - _recycler = BufferRecycler.instance(); + _recycler = bufferRecycler; _inputStream = in; _inputStreamClosed = false; _cfgFullReads = fullReads; - _inputBuffer = _recycler.allocInputBuffer(LZFChunk.MAX_CHUNK_LEN); - _decodedBytes = _recycler.allocDecodeBuffer(LZFChunk.MAX_CHUNK_LEN); + _inputBuffer = bufferRecycler.allocInputBuffer(LZFChunk.MAX_CHUNK_LEN); + _decodedBytes = bufferRecycler.allocDecodeBuffer(LZFChunk.MAX_CHUNK_LEN); } /** diff --git a/src/main/java/com/ning/compress/lzf/LZFOutputStream.java b/src/main/java/com/ning/compress/lzf/LZFOutputStream.java index fe7bdab..c55a8b9 100644 --- a/src/main/java/com/ning/compress/lzf/LZFOutputStream.java +++ b/src/main/java/com/ning/compress/lzf/LZFOutputStream.java @@ -28,7 +28,7 @@ */ public class LZFOutputStream extends FilterOutputStream implements WritableByteChannel { - private static final int OUTPUT_BUFFER_SIZE = LZFChunk.MAX_CHUNK_LEN; + private static final int DEFAULT_OUTPUT_BUFFER_SIZE = LZFChunk.MAX_CHUNK_LEN; private final ChunkEncoder _encoder; private final BufferRecycler _recycler; @@ -58,15 +58,34 @@ public class LZFOutputStream extends FilterOutputStream implements WritableByteC public LZFOutputStream(final OutputStream outputStream) { - this(ChunkEncoderFactory.optimalInstance(OUTPUT_BUFFER_SIZE), outputStream); + this(ChunkEncoderFactory.optimalInstance(DEFAULT_OUTPUT_BUFFER_SIZE), outputStream); } public LZFOutputStream(final ChunkEncoder encoder, final OutputStream outputStream) + { + this(encoder, outputStream, DEFAULT_OUTPUT_BUFFER_SIZE, encoder._recycler); + } + + public LZFOutputStream(final OutputStream outputStream, final BufferRecycler bufferRecycler) + { + this(ChunkEncoderFactory.optimalInstance(bufferRecycler), outputStream, bufferRecycler); + } + + public LZFOutputStream(final ChunkEncoder encoder, final OutputStream outputStream, final BufferRecycler bufferRecycler) + { + this(encoder, outputStream, DEFAULT_OUTPUT_BUFFER_SIZE, bufferRecycler); + } + + public LZFOutputStream(final ChunkEncoder encoder, final OutputStream outputStream, + final int bufferSize, BufferRecycler bufferRecycler) { super(outputStream); _encoder = encoder; - _recycler = BufferRecycler.instance(); - _outputBuffer = _recycler.allocOutputBuffer(OUTPUT_BUFFER_SIZE); + if (bufferRecycler==null) { + bufferRecycler = _encoder._recycler; + } + _recycler = bufferRecycler; + _outputBuffer = bufferRecycler.allocOutputBuffer(bufferSize); _outputStreamClosed = false; } diff --git a/src/main/java/com/ning/compress/lzf/LZFUncompressor.java b/src/main/java/com/ning/compress/lzf/LZFUncompressor.java index e8e756f..0cd6a44 100644 --- a/src/main/java/com/ning/compress/lzf/LZFUncompressor.java +++ b/src/main/java/com/ning/compress/lzf/LZFUncompressor.java @@ -109,14 +109,23 @@ public class LZFUncompressor extends Uncompressor */ public LZFUncompressor(DataHandler handler) { - this(handler, ChunkDecoderFactory.optimalInstance()); + this(handler, ChunkDecoderFactory.optimalInstance(), BufferRecycler.instance()); + } + + public LZFUncompressor(DataHandler handler, BufferRecycler bufferRecycler) { + this(handler, ChunkDecoderFactory.optimalInstance(), bufferRecycler); } public LZFUncompressor(DataHandler handler, ChunkDecoder dec) + { + this(handler, dec, BufferRecycler.instance()); + } + + public LZFUncompressor(DataHandler handler, ChunkDecoder dec, BufferRecycler bufferRecycler) { _handler = handler; _decoder = dec; - _recycler = BufferRecycler.instance(); + _recycler = bufferRecycler; } /* diff --git a/src/main/java/com/ning/compress/lzf/impl/UnsafeChunkEncoder.java b/src/main/java/com/ning/compress/lzf/impl/UnsafeChunkEncoder.java index 3a7648e..6dab20e 100644 --- a/src/main/java/com/ning/compress/lzf/impl/UnsafeChunkEncoder.java +++ b/src/main/java/com/ning/compress/lzf/impl/UnsafeChunkEncoder.java @@ -1,5 +1,6 @@ package com.ning.compress.lzf.impl; +import com.ning.compress.BufferRecycler; import java.lang.reflect.Field; import sun.misc.Unsafe; @@ -44,6 +45,14 @@ public UnsafeChunkEncoder(int totalLength, boolean bogus) { super(totalLength, bogus); } + public UnsafeChunkEncoder(int totalLength, BufferRecycler bufferRecycler) { + super(totalLength, bufferRecycler); + } + + public UnsafeChunkEncoder(int totalLength, BufferRecycler bufferRecycler, boolean bogus) { + super(totalLength, bufferRecycler, bogus); + } + /* /////////////////////////////////////////////////////////////////////// // Shared helper methods diff --git a/src/main/java/com/ning/compress/lzf/impl/UnsafeChunkEncoderBE.java b/src/main/java/com/ning/compress/lzf/impl/UnsafeChunkEncoderBE.java index 72dcedb..bba0139 100644 --- a/src/main/java/com/ning/compress/lzf/impl/UnsafeChunkEncoderBE.java +++ b/src/main/java/com/ning/compress/lzf/impl/UnsafeChunkEncoderBE.java @@ -1,5 +1,6 @@ package com.ning.compress.lzf.impl; +import com.ning.compress.BufferRecycler; import com.ning.compress.lzf.LZFChunk; /** @@ -16,6 +17,14 @@ public UnsafeChunkEncoderBE(int totalLength) { public UnsafeChunkEncoderBE(int totalLength, boolean bogus) { super(totalLength, bogus); } + public UnsafeChunkEncoderBE(int totalLength, BufferRecycler bufferRecycler) { + super(totalLength, bufferRecycler); + } + + public UnsafeChunkEncoderBE(int totalLength, BufferRecycler bufferRecycler, boolean bogus) { + super(totalLength, bufferRecycler, bogus); + } + @Override protected int tryCompress(byte[] in, int inPos, int inEnd, byte[] out, int outPos) diff --git a/src/main/java/com/ning/compress/lzf/impl/UnsafeChunkEncoderLE.java b/src/main/java/com/ning/compress/lzf/impl/UnsafeChunkEncoderLE.java index 21350de..33d1e7d 100644 --- a/src/main/java/com/ning/compress/lzf/impl/UnsafeChunkEncoderLE.java +++ b/src/main/java/com/ning/compress/lzf/impl/UnsafeChunkEncoderLE.java @@ -1,5 +1,6 @@ package com.ning.compress.lzf.impl; +import com.ning.compress.BufferRecycler; import com.ning.compress.lzf.LZFChunk; /** @@ -17,7 +18,15 @@ public UnsafeChunkEncoderLE(int totalLength, boolean bogus) { super(totalLength, bogus); } - @Override + public UnsafeChunkEncoderLE(int totalLength, BufferRecycler bufferRecycler) { + super(totalLength, bufferRecycler); + } + + public UnsafeChunkEncoderLE(int totalLength, BufferRecycler bufferRecycler, boolean bogus) { + super(totalLength, bufferRecycler, bogus); + } + + @Override protected int tryCompress(byte[] in, int inPos, int inEnd, byte[] out, int outPos) { final int[] hashTable = _hashTable; diff --git a/src/main/java/com/ning/compress/lzf/impl/UnsafeChunkEncoders.java b/src/main/java/com/ning/compress/lzf/impl/UnsafeChunkEncoders.java index 2ae6777..36489e8 100644 --- a/src/main/java/com/ning/compress/lzf/impl/UnsafeChunkEncoders.java +++ b/src/main/java/com/ning/compress/lzf/impl/UnsafeChunkEncoders.java @@ -11,6 +11,7 @@ package com.ning.compress.lzf.impl; +import com.ning.compress.BufferRecycler; import java.nio.ByteOrder; @@ -39,4 +40,18 @@ public static UnsafeChunkEncoder createNonAllocatingEncoder(int totalLength) { } return new UnsafeChunkEncoderBE(totalLength, false); } + + public static UnsafeChunkEncoder createEncoder(int totalLength, BufferRecycler bufferRecycler) { + if (LITTLE_ENDIAN) { + return new UnsafeChunkEncoderLE(totalLength, bufferRecycler); + } + return new UnsafeChunkEncoderBE(totalLength, bufferRecycler); + } + + public static UnsafeChunkEncoder createNonAllocatingEncoder(int totalLength, BufferRecycler bufferRecycler) { + if (LITTLE_ENDIAN) { + return new UnsafeChunkEncoderLE(totalLength, bufferRecycler, false); + } + return new UnsafeChunkEncoderBE(totalLength, bufferRecycler, false); + } } diff --git a/src/main/java/com/ning/compress/lzf/impl/VanillaChunkEncoder.java b/src/main/java/com/ning/compress/lzf/impl/VanillaChunkEncoder.java index 9e68ac6..74a52d5 100644 --- a/src/main/java/com/ning/compress/lzf/impl/VanillaChunkEncoder.java +++ b/src/main/java/com/ning/compress/lzf/impl/VanillaChunkEncoder.java @@ -1,5 +1,6 @@ package com.ning.compress.lzf.impl; +import com.ning.compress.BufferRecycler; import com.ning.compress.lzf.ChunkEncoder; import com.ning.compress.lzf.LZFChunk; @@ -22,10 +23,31 @@ protected VanillaChunkEncoder(int totalLength, boolean bogus) { super(totalLength, bogus); } + /** + * @param totalLength Total encoded length; used for calculating size + * of hash table to use + * @param bufferRecycler The BufferRecycler instance + */ + public VanillaChunkEncoder(int totalLength, BufferRecycler bufferRecycler) { + super(totalLength, bufferRecycler); + } + + /** + * Alternate constructor used when we want to avoid allocation encoding + * buffer, in cases where caller wants full control over allocations. + */ + protected VanillaChunkEncoder(int totalLength, BufferRecycler bufferRecycler, boolean bogus) { + super(totalLength, bufferRecycler, bogus); + } + public static VanillaChunkEncoder nonAllocatingEncoder(int totalLength) { return new VanillaChunkEncoder(totalLength, true); } + public static VanillaChunkEncoder nonAllocatingEncoder(int totalLength, BufferRecycler bufferRecycler) { + return new VanillaChunkEncoder(totalLength, bufferRecycler, true); + } + /* /////////////////////////////////////////////////////////////////////// // Abstract method implementations diff --git a/src/main/java/com/ning/compress/lzf/parallel/PLZFOutputStream.java b/src/main/java/com/ning/compress/lzf/parallel/PLZFOutputStream.java index fe52761..0236dec 100644 --- a/src/main/java/com/ning/compress/lzf/parallel/PLZFOutputStream.java +++ b/src/main/java/com/ning/compress/lzf/parallel/PLZFOutputStream.java @@ -41,7 +41,7 @@ */ public class PLZFOutputStream extends FilterOutputStream implements WritableByteChannel { - private static final int OUTPUT_BUFFER_SIZE = LZFChunk.MAX_CHUNK_LEN; + private static final int DEFAULT_OUTPUT_BUFFER_SIZE = LZFChunk.MAX_CHUNK_LEN; protected byte[] _outputBuffer; protected int _position = 0; @@ -65,16 +65,20 @@ public class PLZFOutputStream extends FilterOutputStream implements WritableByte */ public PLZFOutputStream(final OutputStream outputStream) { - this(outputStream, getNThreads()); + this(outputStream, DEFAULT_OUTPUT_BUFFER_SIZE, getNThreads()); } protected PLZFOutputStream(final OutputStream outputStream, int nThreads) { + this(outputStream, DEFAULT_OUTPUT_BUFFER_SIZE, nThreads); + } + + protected PLZFOutputStream(final OutputStream outputStream, final int bufferSize, int nThreads) { super(outputStream); _outputStreamClosed = false; compressExecutor = new ThreadPoolExecutor(nThreads, nThreads, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue()); // unbounded ((ThreadPoolExecutor)compressExecutor).allowCoreThreadTimeOut(true); writeExecutor = Executors.newSingleThreadExecutor(); // unbounded - blockManager = new BlockManager(nThreads * 2, OUTPUT_BUFFER_SIZE); // this is where the bounds will be enforced! + blockManager = new BlockManager(nThreads * 2, bufferSize); // this is where the bounds will be enforced! _outputBuffer = blockManager.getBlockFromPool(); } diff --git a/src/main/java/com/ning/compress/lzf/util/ChunkEncoderFactory.java b/src/main/java/com/ning/compress/lzf/util/ChunkEncoderFactory.java index af2134a..f61379f 100644 --- a/src/main/java/com/ning/compress/lzf/util/ChunkEncoderFactory.java +++ b/src/main/java/com/ning/compress/lzf/util/ChunkEncoderFactory.java @@ -1,5 +1,6 @@ package com.ning.compress.lzf.util; +import com.ning.compress.BufferRecycler; import com.ning.compress.lzf.ChunkEncoder; import com.ning.compress.lzf.LZFChunk; import com.ning.compress.lzf.impl.UnsafeChunkEncoders; @@ -35,6 +36,8 @@ public static ChunkEncoder optimalInstance() { * non-standard platforms it may be necessary to either directly load * instances, or use {@link #safeInstance}. * + *

Uses a ThreadLocal soft-referenced BufferRecycler instance. + * * @param totalLength Expected total length of content to compress; only matters * for content that is smaller than maximum chunk size (64k), to optimize * encoding hash tables @@ -50,6 +53,8 @@ public static ChunkEncoder optimalInstance(int totalLength) { /** * Factory method for constructing encoder that is always passed buffer * externally, so that it will not (nor need) allocate encoding buffer. + * + *

Uses a ThreadLocal soft-referenced BufferRecycler instance. */ public static ChunkEncoder optimalNonAllocatingInstance(int totalLength) { try { @@ -68,9 +73,12 @@ public static ChunkEncoder optimalNonAllocatingInstance(int totalLength) { public static ChunkEncoder safeInstance() { return safeInstance(LZFChunk.MAX_CHUNK_LEN); } + /** * Method that can be used to ensure that a ""safe"" compressor instance is loaded. * Safe here means that it should work on any and all Java platforms. + * + *

Uses a ThreadLocal soft-referenced BufferRecycler instance. * * @param totalLength Expected total length of content to compress; only matters * for content that is smaller than maximum chunk size (64k), to optimize @@ -83,8 +91,82 @@ public static ChunkEncoder safeInstance(int totalLength) { /** * Factory method for constructing encoder that is always passed buffer * externally, so that it will not (nor need) allocate encoding buffer. + * + *

Uses a ThreadLocal soft-referenced BufferRecycler instance. */ public static ChunkEncoder safeNonAllocatingInstance(int totalLength) { return VanillaChunkEncoder.nonAllocatingEncoder(totalLength); } + + /** + * Convenience method, equivalent to: + * + * return optimalInstance(LZFChunk.MAX_CHUNK_LEN, bufferRecycler); + * + */ + public static ChunkEncoder optimalInstance(BufferRecycler bufferRecycler) { + return optimalInstance(LZFChunk.MAX_CHUNK_LEN, bufferRecycler); + } + + /** + * Method to use for getting compressor instance that uses the most optimal + * available methods for underlying data access. It should be safe to call + * this method as implementations are dynamically loaded; however, on some + * non-standard platforms it may be necessary to either directly load + * instances, or use {@link #safeInstance}. + * + * @param totalLength Expected total length of content to compress; only matters + * for content that is smaller than maximum chunk size (64k), to optimize + * encoding hash tables + * @param bufferRecycler The BufferRecycler instance + */ + public static ChunkEncoder optimalInstance(int totalLength, BufferRecycler bufferRecycler) { + try { + return UnsafeChunkEncoders.createEncoder(totalLength, bufferRecycler); + } catch (Exception e) { + return safeInstance(totalLength, bufferRecycler); + } + } + + /** + * Factory method for constructing encoder that is always passed buffer + * externally, so that it will not (nor need) allocate encoding buffer. + */ + public static ChunkEncoder optimalNonAllocatingInstance(int totalLength, BufferRecycler bufferRecycler) { + try { + return UnsafeChunkEncoders.createNonAllocatingEncoder(totalLength, bufferRecycler); + } catch (Exception e) { + return safeNonAllocatingInstance(totalLength, bufferRecycler); + } + } + + /** + * Convenience method, equivalent to: + * + * return safeInstance(LZFChunk.MAX_CHUNK_LEN, bufferRecycler); + * + */ + public static ChunkEncoder safeInstance(BufferRecycler bufferRecycler) { + return safeInstance(LZFChunk.MAX_CHUNK_LEN, bufferRecycler); + } + /** + * Method that can be used to ensure that a ""safe"" compressor instance is loaded. + * Safe here means that it should work on any and all Java platforms. + * + * @param totalLength Expected total length of content to compress; only matters + * for content that is smaller than maximum chunk size (64k), to optimize + * encoding hash tables + * @param bufferRecycler The BufferRecycler instance + */ + public static ChunkEncoder safeInstance(int totalLength, BufferRecycler bufferRecycler) { + return new VanillaChunkEncoder(totalLength, bufferRecycler); + } + + /** + * Factory method for constructing encoder that is always passed buffer + * externally, so that it will not (nor need) allocate encoding buffer. + */ + public static ChunkEncoder safeNonAllocatingInstance(int totalLength, BufferRecycler bufferRecycler) { + return VanillaChunkEncoder.nonAllocatingEncoder(totalLength, bufferRecycler); + } } diff --git a/src/main/java/com/ning/compress/lzf/util/LZFFileInputStream.java b/src/main/java/com/ning/compress/lzf/util/LZFFileInputStream.java index 27e5d25..19f7caa 100644 --- a/src/main/java/com/ning/compress/lzf/util/LZFFileInputStream.java +++ b/src/main/java/com/ning/compress/lzf/util/LZFFileInputStream.java @@ -77,47 +77,62 @@ public class LZFFileInputStream */ public LZFFileInputStream(File file) throws FileNotFoundException { - this(file, ChunkDecoderFactory.optimalInstance()); + this(file, ChunkDecoderFactory.optimalInstance(), BufferRecycler.instance()); } public LZFFileInputStream(FileDescriptor fdObj) { - this(fdObj, ChunkDecoderFactory.optimalInstance()); + this(fdObj, ChunkDecoderFactory.optimalInstance(), BufferRecycler.instance()); } public LZFFileInputStream(String name) throws FileNotFoundException { - this(name, ChunkDecoderFactory.optimalInstance()); + this(name, ChunkDecoderFactory.optimalInstance(), BufferRecycler.instance()); } public LZFFileInputStream(File file, ChunkDecoder decompressor) throws FileNotFoundException + { + this(file, decompressor, BufferRecycler.instance()); + } + + public LZFFileInputStream(FileDescriptor fdObj, ChunkDecoder decompressor) + { + this(fdObj, decompressor, BufferRecycler.instance()); + } + + public LZFFileInputStream(String name, ChunkDecoder decompressor) throws FileNotFoundException + { + this(name, decompressor, BufferRecycler.instance()); + } + + public LZFFileInputStream(File file, ChunkDecoder decompressor, BufferRecycler bufferRecycler) throws FileNotFoundException { super(file); _decompressor = decompressor; - _recycler = BufferRecycler.instance(); + _recycler = bufferRecycler; _inputStreamClosed = false; - _inputBuffer = _recycler.allocInputBuffer(LZFChunk.MAX_CHUNK_LEN); - _decodedBytes = _recycler.allocDecodeBuffer(LZFChunk.MAX_CHUNK_LEN); + _inputBuffer = bufferRecycler.allocInputBuffer(LZFChunk.MAX_CHUNK_LEN); + _decodedBytes = bufferRecycler.allocDecodeBuffer(LZFChunk.MAX_CHUNK_LEN); _wrapper = new Wrapper(); } - public LZFFileInputStream(FileDescriptor fdObj, ChunkDecoder decompressor) + public LZFFileInputStream(FileDescriptor fdObj, ChunkDecoder decompressor, BufferRecycler bufferRecycler) { super(fdObj); _decompressor = decompressor; - _recycler = BufferRecycler.instance(); + _recycler = bufferRecycler; _inputStreamClosed = false; - _inputBuffer = _recycler.allocInputBuffer(LZFChunk.MAX_CHUNK_LEN); - _decodedBytes = _recycler.allocDecodeBuffer(LZFChunk.MAX_CHUNK_LEN); + _inputBuffer = bufferRecycler.allocInputBuffer(LZFChunk.MAX_CHUNK_LEN); + _decodedBytes = bufferRecycler.allocDecodeBuffer(LZFChunk.MAX_CHUNK_LEN); _wrapper = new Wrapper(); } - public LZFFileInputStream(String name, ChunkDecoder decompressor) throws FileNotFoundException + public LZFFileInputStream(String name, ChunkDecoder decompressor, BufferRecycler bufferRecycler) throws FileNotFoundException { super(name); _decompressor = decompressor; - _recycler = BufferRecycler.instance(); + _recycler = bufferRecycler; _inputStreamClosed = false; - _inputBuffer = _recycler.allocInputBuffer(LZFChunk.MAX_CHUNK_LEN); - _decodedBytes = _recycler.allocDecodeBuffer(LZFChunk.MAX_CHUNK_LEN); + _inputBuffer = bufferRecycler.allocInputBuffer(LZFChunk.MAX_CHUNK_LEN); + _decodedBytes = bufferRecycler.allocDecodeBuffer(LZFChunk.MAX_CHUNK_LEN); _wrapper = new Wrapper(); } diff --git a/src/main/java/com/ning/compress/lzf/util/LZFFileOutputStream.java b/src/main/java/com/ning/compress/lzf/util/LZFFileOutputStream.java index b20aa5d..3a5f457 100644 --- a/src/main/java/com/ning/compress/lzf/util/LZFFileOutputStream.java +++ b/src/main/java/com/ning/compress/lzf/util/LZFFileOutputStream.java @@ -86,42 +86,65 @@ public LZFFileOutputStream(String name, boolean append) throws FileNotFoundExcep } public LZFFileOutputStream(ChunkEncoder encoder, File file) throws FileNotFoundException { + this(encoder, file, encoder.getBufferRecycler()); + } + + public LZFFileOutputStream(ChunkEncoder encoder, File file, boolean append) throws FileNotFoundException { + this(encoder, file, append, encoder.getBufferRecycler()); + } + + public LZFFileOutputStream(ChunkEncoder encoder, FileDescriptor fdObj) { + this(encoder, fdObj, encoder.getBufferRecycler()); + } + + public LZFFileOutputStream(ChunkEncoder encoder, String name) throws FileNotFoundException { + this(encoder, name, encoder.getBufferRecycler()); + } + + public LZFFileOutputStream(ChunkEncoder encoder, String name, boolean append) throws FileNotFoundException { + this(encoder, name, append, encoder.getBufferRecycler()); + } + + public LZFFileOutputStream(ChunkEncoder encoder, File file, BufferRecycler bufferRecycler) throws FileNotFoundException { super(file); _encoder = encoder; - _recycler = BufferRecycler.instance(); - _outputBuffer = _recycler.allocOutputBuffer(OUTPUT_BUFFER_SIZE); + if (bufferRecycler==null) { + bufferRecycler = encoder.getBufferRecycler(); + } + _recycler = bufferRecycler; + _outputBuffer = bufferRecycler.allocOutputBuffer(OUTPUT_BUFFER_SIZE); _wrapper = new Wrapper(); } - public LZFFileOutputStream(ChunkEncoder encoder, File file, boolean append) throws FileNotFoundException { + public LZFFileOutputStream(ChunkEncoder encoder, File file, boolean append, BufferRecycler bufferRecycler) throws FileNotFoundException { super(file, append); _encoder = encoder; - _recycler = BufferRecycler.instance(); - _outputBuffer = _recycler.allocOutputBuffer(OUTPUT_BUFFER_SIZE); + _recycler = bufferRecycler; + _outputBuffer = bufferRecycler.allocOutputBuffer(OUTPUT_BUFFER_SIZE); _wrapper = new Wrapper(); } - public LZFFileOutputStream(ChunkEncoder encoder, FileDescriptor fdObj) { + public LZFFileOutputStream(ChunkEncoder encoder, FileDescriptor fdObj, BufferRecycler bufferRecycler) { super(fdObj); _encoder = encoder; - _recycler = BufferRecycler.instance(); - _outputBuffer = _recycler.allocOutputBuffer(OUTPUT_BUFFER_SIZE); + _recycler = bufferRecycler; + _outputBuffer = bufferRecycler.allocOutputBuffer(OUTPUT_BUFFER_SIZE); _wrapper = new Wrapper(); } - public LZFFileOutputStream(ChunkEncoder encoder, String name) throws FileNotFoundException { + public LZFFileOutputStream(ChunkEncoder encoder, String name, BufferRecycler bufferRecycler) throws FileNotFoundException { super(name); _encoder = encoder; - _recycler = BufferRecycler.instance(); - _outputBuffer = _recycler.allocOutputBuffer(OUTPUT_BUFFER_SIZE); + _recycler = bufferRecycler; + _outputBuffer = bufferRecycler.allocOutputBuffer(OUTPUT_BUFFER_SIZE); _wrapper = new Wrapper(); } - public LZFFileOutputStream(ChunkEncoder encoder, String name, boolean append) throws FileNotFoundException { + public LZFFileOutputStream(ChunkEncoder encoder, String name, boolean append, BufferRecycler bufferRecycler) throws FileNotFoundException { super(name, append); _encoder = encoder; - _recycler = BufferRecycler.instance(); - _outputBuffer = _recycler.allocOutputBuffer(OUTPUT_BUFFER_SIZE); + _recycler = bufferRecycler; + _outputBuffer = bufferRecycler.allocOutputBuffer(OUTPUT_BUFFER_SIZE); _wrapper = new Wrapper(); }" d3ec4cab768b7062fa7625d623402f25f349028c,Mylyn Reviews,"380843: index commit messages of changesets Created custom filter for changesets, which works better with task numbers like used in jira (Prefix-Number). Task-Url: https://bugs.eclipse.org/bugs/show_bug.cgi?id=380843 Change-Id: Ice1cf8e3a558c36d9e832312a0a6259e7f6e7e86 ",a,https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews,"diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/BracketFilter.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/BracketFilter.java new file mode 100644 index 00000000..df4575c3 --- /dev/null +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/BracketFilter.java @@ -0,0 +1,51 @@ +/******************************************************************************* + * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.versions.tasks.mapper.internal; + +import java.util.Arrays; + +import org.apache.lucene.analysis.TokenFilter; +import org.apache.lucene.analysis.TokenStream; +import org.apache.lucene.analysis.tokenattributes.TermAttribute; + +/** + * + * @author Kilian Matt + * + */ +public class BracketFilter extends TokenFilter { + private TermAttribute attribute; + private char[] illegalChars= {'(',')','[',']','{','}'}; + public BracketFilter(TokenStream in) { + super(in); + attribute = (TermAttribute) addAttribute(TermAttribute.class); + Arrays.sort(illegalChars); + } + + /** Returns the next token in the stream, or null at EOS. + *

Removes 's from the end of words. + *

Removes dots from acronyms. + */ + public final boolean incrementToken() throws java.io.IOException { + if(!input.incrementToken()) return false; + + char[] buffer = attribute.termBuffer(); + char[] target = new char[buffer.length]; + int targetPos=0; + for(int i =0; i < buffer.length; i++) { + if(Arrays.binarySearch(illegalChars,buffer[i])<0) { + target[targetPos++] = buffer[i]; + } + } + attribute.setTermBuffer(target,0,targetPos); + return true; + } +} diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetAnalyzer.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetAnalyzer.java new file mode 100644 index 00000000..ae61a595 --- /dev/null +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetAnalyzer.java @@ -0,0 +1,43 @@ +/******************************************************************************* + * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.versions.tasks.mapper.internal; + +import java.io.Reader; + +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.analysis.KeywordAnalyzer; +import org.apache.lucene.analysis.PerFieldAnalyzerWrapper; +import org.apache.lucene.analysis.TokenStream; +import org.apache.lucene.analysis.WhitespaceAnalyzer; +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.util.Version; + +/** + * + * @author Kilian Matt + * + */ +public class ChangeSetAnalyzer { + public static Analyzer get() { + PerFieldAnalyzerWrapper analyzer = new PerFieldAnalyzerWrapper(new StandardAnalyzer(Version.LUCENE_CURRENT)); + analyzer.addAnalyzer(IndexedFields.REPOSITORY.getIndexKey(), new KeywordAnalyzer()); + analyzer.addAnalyzer(IndexedFields.COMMIT_MESSAGE.getIndexKey(), new Analyzer() { + @Override + public TokenStream tokenStream(String fieldName, Reader reader) { + WhitespaceAnalyzer delegate =new WhitespaceAnalyzer(); + TokenStream tokenStream = delegate.tokenStream(fieldName, reader); + BracketFilter filteredStream = new BracketFilter(tokenStream); + return filteredStream; + } + }); + return analyzer; + } + } \ No newline at end of file diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexer.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexer.java index d7460e44..08a0058b 100644 --- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexer.java +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexer.java @@ -9,14 +9,11 @@ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.versions.tasks.mapper.internal; + import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; -import org.apache.lucene.LucenePackage; -import org.apache.lucene.analysis.KeywordAnalyzer; -import org.apache.lucene.analysis.PerFieldAnalyzerWrapper; -import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.Field.Store; @@ -25,22 +22,15 @@ import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriter.MaxFieldLength; import org.apache.lucene.index.Term; +import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; -import org.apache.lucene.search.DisjunctionMaxQuery; import org.apache.lucene.search.IndexSearcher; -import org.apache.lucene.search.PhraseQuery; import org.apache.lucene.search.PrefixQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; -import org.apache.lucene.search.BooleanClause.Occur; -import org.apache.lucene.search.spans.SpanOrQuery; -import org.apache.lucene.search.spans.SpanQuery; -import org.apache.lucene.search.spans.SpanTermQuery; import org.apache.lucene.store.NIOFSDirectory; -import org.apache.lucene.util.Version; -import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.mylyn.tasks.core.ITask; @@ -51,7 +41,7 @@ import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetSource; /** - * + * * @author Kilian Matt */ public class ChangeSetIndexer implements IChangeSetIndexSearcher { @@ -67,12 +57,10 @@ public ChangeSetIndexer(File directory, IChangeSetSource source) { this.source = source; } + public void reindex(IProgressMonitor monitor) { try { - PerFieldAnalyzerWrapper analyzer = new PerFieldAnalyzerWrapper(new StandardAnalyzer(Version.LUCENE_CURRENT)); - analyzer.addAnalyzer(IndexedFields.REPOSITORY.getIndexKey(), new KeywordAnalyzer()); - indexWriter = new IndexWriter(new NIOFSDirectory(indexDirectory), - analyzer, true, MaxFieldLength.UNLIMITED); + indexWriter = new IndexWriter(new NIOFSDirectory(indexDirectory),ChangeSetAnalyzer.get(), true, MaxFieldLength.UNLIMITED); IChangeSetIndexer indexer = new IChangeSetIndexer() { @@ -96,29 +84,29 @@ public void index(ChangeSet changeset) { } } - public int search(ITask task, String scmRepositoryUrl, int resultsLimit, IChangeSetCollector collector) throws CoreException { + public int search(ITask task, String scmRepositoryUrl, int resultsLimit,IChangeSetCollector collector) throws CoreException { int count = 0; IndexReader indexReader = getIndexReader(); if (indexReader != null) { IndexSearcher indexSearcher = new IndexSearcher(indexReader); try { - Query query = createQuery(task,scmRepositoryUrl); + Query query = createQuery(task, scmRepositoryUrl); TopDocs results = indexSearcher.search(query, resultsLimit); for (ScoreDoc scoreDoc : results.scoreDocs) { Document document = indexReader.document(scoreDoc.doc); count++; - if(count > resultsLimit) + if (count > resultsLimit) break; - - + String revision = document.getField(IndexedFields.REVISION.getIndexKey()).stringValue(); - String repositoryUrl =document.getField(IndexedFields.REPOSITORY.getIndexKey()).stringValue(); - + String repositoryUrl = document.getField(IndexedFields.REPOSITORY.getIndexKey()).stringValue(); + collector.collect(revision, repositoryUrl); } } catch (IOException e) { -// StatusHandler.log(new Status(IStatus.ERROR, org.eclipse.mylyn.versions.tasks.ui.internal.TaPLUGIN_ID, -//""Unexpected failure within task list index"", e)); //$NON-NLS-1$ + // StatusHandler.log(new Status(IStatus.ERROR, + // org.eclipse.mylyn.versions.tasks.ui.internal.TaPLUGIN_ID, + //""Unexpected failure within task list index"", e)); //$NON-NLS-1$ } finally { try { indexSearcher.close(); @@ -132,20 +120,22 @@ public int search(ITask task, String scmRepositoryUrl, int resultsLimit, IChange } private Query createQuery(ITask task, String repositoryUrl) { - BooleanQuery query =new BooleanQuery(); + BooleanQuery query = new BooleanQuery(); query.setMinimumNumberShouldMatch(1); - query.add(new TermQuery(new Term(IndexedFields.REPOSITORY.getIndexKey(),repositoryUrl)),Occur.MUST); - query.add(new PrefixQuery(new Term(IndexedFields.COMMIT_MESSAGE.getIndexKey(),task.getUrl())),Occur.SHOULD); - query.add(new PrefixQuery(new Term(IndexedFields.COMMIT_MESSAGE.getIndexKey(),task.getTaskId())),Occur.SHOULD); + query.add(new TermQuery(new Term(IndexedFields.REPOSITORY.getIndexKey(), repositoryUrl)), Occur.MUST); + query.add(new PrefixQuery(new Term(IndexedFields.COMMIT_MESSAGE.getIndexKey(), task.getUrl())), Occur.SHOULD); + query.add(new PrefixQuery(new Term(IndexedFields.COMMIT_MESSAGE.getIndexKey(), task.getTaskId())), Occur.SHOULD); + query.add(new PrefixQuery(new Term(IndexedFields.COMMIT_MESSAGE.getIndexKey(), task.getTaskKey())), Occur.SHOULD); + return query; } - private IndexReader getIndexReader() { try { synchronized (this) { if (indexReader == null) { - indexReader = IndexReader.open(new NIOFSDirectory(indexDirectory), true); + indexReader = IndexReader.open(new NIOFSDirectory( + indexDirectory), true); } return indexReader; } diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexerTest.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexerTest.java index f909b736..f7aa8c42 100644 --- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexerTest.java +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexerTest.java @@ -36,15 +36,16 @@ import org.junit.Test; /** - * + * * @author Kilian Matt * */ +@SuppressWarnings(""restriction"") public class ChangeSetIndexerTest { protected static final String REPO_URL = ""http://git.eclipse.org/c/mylyn/org.eclipse.mylyn.versions.git""; private ChangeSetIndexer indexer; - + @Before public void prepareIndex() { File dir = createTempDirectoryForIndex(); @@ -61,7 +62,7 @@ public void testSingleResult() throws CoreException{ collectors.expect(""1"", REPO_URL); assertEquals(1, indexer.search(task,REPO_URL, 5,collectors)); collectors.verifyAllExpectations(); - } + } @Test public void testMultipleResults() throws CoreException{ ITask task = new MockTask(REPO_URL,""2""); @@ -73,13 +74,33 @@ public void testMultipleResults() throws CoreException{ collectors.verifyAllExpectations(); } + @Test + public void testFindByTaskUrl() throws CoreException{ + ITask task = new MockTask(REPO_URL,""4""); + task.setUrl(REPO_URL+""/4""); + ExpectingChangeSetCollector collectors= new ExpectingChangeSetCollector(); + collectors.expect(""4"", REPO_URL); + assertEquals(1, indexer.search(task,REPO_URL, 5,collectors)); + collectors.verifyAllExpectations(); + } + @Test + public void testComplexTaskKeys() throws CoreException{ + ITask task = new MockTask(REPO_URL,""2131""); + task.setTaskKey(""SPR-9030""); + task.setUrl(REPO_URL+""/1""); + ExpectingChangeSetCollector collectors= new ExpectingChangeSetCollector(); + collectors.expect(""5"", REPO_URL); + collectors.expect(""6"", REPO_URL); + assertEquals(2, indexer.search(task,REPO_URL, 5,collectors)); + collectors.verifyAllExpectations(); + } static class ExpectingChangeSetCollector implements IChangeSetCollector{ private List expected=new LinkedList(); void expect(String revision, String repositoryUrl){ this.expected.add(new Pair(revision,repositoryUrl)); } - + public void verifyAllExpectations() { if(expected.size()>0){ fail( expected.size() + "" expected changesets not collected""); @@ -108,16 +129,20 @@ public void collect(String revision, String repositoryUrl) } private ListChangeSetSource createIndexerSource() { ScmRepository repository=new ScmRepository(null, """", REPO_URL); - ScmRepository otherRepo=new ScmRepository(null, """", ""http://git.eclipse.org/c/mylyn/org.eclipse.mylyn.reviews.git""); + ScmRepository otherRepo=new ScmRepository(null, """", ""http://git.eclipse.org/c/mylyn/org.eclipse.mylyn.reviews.git""); ListChangeSetSource source = new ListChangeSetSource(Arrays.asList( new ChangeSet(new ScmUser(""test"", ""Name"", ""test@eclipse.org""), new Date(), ""1"", ""commit message 1"", repository, new ArrayList()), new ChangeSet(new ScmUser(""test"", ""Name"", ""test@eclipse.org""), new Date(), ""1"", ""commit message 1"", otherRepo, new ArrayList()), new ChangeSet(new ScmUser(""test"", ""Name"", ""test@eclipse.org""), new Date(), ""2"", ""commit message 2"", repository, new ArrayList()), - new ChangeSet(new ScmUser(""test"", ""Name"", ""test@eclipse.org""), new Date(), ""3"", ""commit message 2"", repository, new ArrayList()) + new ChangeSet(new ScmUser(""test"", ""Name"", ""test@eclipse.org""), new Date(), ""3"", ""commit message 2"", repository, new ArrayList()), + new ChangeSet(new ScmUser(""test"", ""Name"", ""test@eclipse.org""), new Date(), ""4"", ""another commit message with url http://git.eclipse.org/c/mylyn/org.eclipse.mylyn.versions.git/4 "", repository, new ArrayList()), + + new ChangeSet(new ScmUser(""test"", ""Name"", ""test@eclipse.org""), new Date(), ""5"", ""SPR-9030: Test"", repository, new ArrayList()), + new ChangeSet(new ScmUser(""test"", ""Name"", ""test@eclipse.org""), new Date(), ""6"", ""Fixed Bug (SPR-9030)"", repository, new ArrayList()) )); return source; } - + class ListChangeSetSource implements IChangeSetSource { private List changesets; public ListChangeSetSource(List changesets){ @@ -131,7 +156,7 @@ public void fetchAllChangesets(IProgressMonitor monitor, } } } - + private File createTempDirectoryForIndex() { File dir = null; try { @@ -144,7 +169,7 @@ private File createTempDirectoryForIndex() { } return dir; } - - - + + + }" 36cfc1272adb7973aeb7437ac689ff2168c9777d,Vala,"glib-2.0: Add more GMarkup bindings Add g_markup_collect_attributes, g_markup_parser_context_push, g_markup_parser_context_pop, and GMarkupCollectType bindings, based on patch by Yu Feng, fixes bug 564704. ",a,https://github.com/GNOME/vala/,"diff --git a/vapi/glib-2.0.vapi b/vapi/glib-2.0.vapi index d1d075f0de..ff9474eb3f 100644 --- a/vapi/glib-2.0.vapi +++ b/vapi/glib-2.0.vapi @@ -2684,7 +2684,8 @@ namespace GLib { PARSE, UNKNOWN_ELEMENT, UNKNOWN_ATTRIBUTE, - INVALID_CONTENT + INVALID_CONTENT, + MISSING_ATTRIBUTE } [CCode (cprefix = ""G_MARKUP_"", has_type_id = false)] @@ -2701,6 +2702,8 @@ namespace GLib { public weak string get_element (); public weak SList get_element_stack (); public void get_position (out int line_number, out int char_number); + public void push (MarkupParser parser, void* user_data); + public void* pop (MarkupParser parser); } public delegate void MarkupParserStartElementFunc (MarkupParseContext context, string element_name, [CCode (array_length = false, array_null_terminated = true)] string[] attribute_names, [CCode (array_length = false, array_null_terminated = true)] string[] attribute_values) throws MarkupError; @@ -2722,9 +2725,21 @@ namespace GLib { } namespace Markup { + [CCode (cprefix = ""G_MARKUP_COLLECT_"", has_type_id = false)] + public enum CollectType { + INVALID, + STRING, + STRDUP, + BOOLEAN, + TRISTATE, + OPTIONAL + } + public static string escape_text (string text, long length = -1); [PrintfFormat] public static string printf_escaped (string format, ...); + [CCode (sentinel = ""G_MARKUP_COLLECT_INVALID"")] + public static bool collect_attributes (string element_name, string[] attribute_names, string[] attribute_values, ...) throws MarkupError; } /* Key-value file parser */" fef434b11eb3abf88fca6ac3073a5025447a646d,orientdb,Fixed issue -1521 about JSON management of- embedded lists with different types--,c,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerSchemaAware2CSV.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerSchemaAware2CSV.java index f4490b73182..7df87652f56 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerSchemaAware2CSV.java +++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerSchemaAware2CSV.java @@ -212,13 +212,9 @@ else if (firstValue instanceof Enum) else { linkedType = OType.getTypeByClass(firstValue.getClass()); - if (linkedType != OType.LINK) { - // EMBEDDED FOR SURE SINCE IT CONTAINS JAVA TYPES - if (linkedType == null) { - linkedType = OType.EMBEDDED; - // linkedClass = new OClass(firstValue.getClass()); - } - } + if (linkedType != OType.LINK) + // EMBEDDED FOR SURE DON'T USE THE LINKED TYPE + linkedType = null; } if (type == null) diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/JSONTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/JSONTest.java index 411fe57fa61..e702f9d9fc1 100755 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/JSONTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/JSONTest.java @@ -15,7 +15,12 @@ */ package com.orientechnologies.orient.test.database.auto; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.testng.Assert; import org.testng.annotations.Parameters; @@ -37,6 +42,11 @@ public class JSONTest { private String url; +// public static final void main(String[] args) throws Exception { +// JSONTest test = new JSONTest(""memory:test""); +// test.testList(); +// } + @Parameters(value = ""url"") public JSONTest(final String iURL) { url = iURL; @@ -687,4 +697,17 @@ public void nestedJsonTest() { db.close(); } + + @Test + public void testList() throws Exception { + ODocument documentSource = new ODocument(); + documentSource.fromJSON(""{\""list\"" : [\""string\"", 42]}""); + + ODocument documentTarget = new ODocument(); + documentTarget.fromStream(documentSource.toStream()); + + OTrackedList list = documentTarget.field(""list"", OType.EMBEDDEDLIST); + Assert.assertEquals(list.get(0), ""string""); + Assert.assertEquals(list.get(1), 42); + } }" ba424c200bb5b1321f2a8872dfbb1b6f95e2eab0,tapiji,"Adapts the namespace of all TapiJI plug-ins to org.eclipselabs.tapiji.*. ",p,https://github.com/tapiji/tapiji,"diff --git a/at.ac.tuwien.inso.eclipse.i18n.java/.project b/at.ac.tuwien.inso.eclipse.i18n.java/.project index fc4b668e..fe4d5b8a 100644 --- a/at.ac.tuwien.inso.eclipse.i18n.java/.project +++ b/at.ac.tuwien.inso.eclipse.i18n.java/.project @@ -1,6 +1,6 @@ - at.ac.tuwien.inso.eclipse.i18n.java + org.eclipselabs.tapiji.tools.java diff --git a/at.ac.tuwien.inso.eclipse.i18n.java/META-INF/MANIFEST.MF b/at.ac.tuwien.inso.eclipse.i18n.java/META-INF/MANIFEST.MF index d28b965f..979bf42a 100644 --- a/at.ac.tuwien.inso.eclipse.i18n.java/META-INF/MANIFEST.MF +++ b/at.ac.tuwien.inso.eclipse.i18n.java/META-INF/MANIFEST.MF @@ -1,17 +1,17 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: JavaBuilderExtension -Bundle-SymbolicName: at.ac.tuwien.inso.eclipse.i18n.java;singleton:=true +Bundle-SymbolicName: org.eclipselabs.tapiji.tools.java;singleton:=true Bundle-Version: 0.0.1.qualifier Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: at.ac.tuwien.inso.eclipse.i18n;bundle-version=""0.0.1"", - org.eclipse.core.resources;bundle-version=""3.6.0"", +Require-Bundle: org.eclipse.core.resources;bundle-version=""3.6.0"", org.eclipse.jdt.core;bundle-version=""3.6.0"", org.eclipse.core.runtime;bundle-version=""3.6.0"", org.eclipse.jdt.ui;bundle-version=""3.6.0"", - org.eclipse.jface -Import-Package: at.ac.tuwien.inso.eclipse.rbe.model.bundle, - at.ac.tuwien.inso.eclipse.rbe.ui.wizards, + org.eclipse.jface, + org.eclipselabs.tapiji.tools.core;bundle-version=""0.0.1"" +Import-Package: org.eclipselabs.tapiji.translator.rbe.model.bundle, + org.eclipselabs.tapiji.translator.rbe.ui.wizards, org.eclipse.core.filebuffers, org.eclipse.jface.dialogs, org.eclipse.jface.text, diff --git a/at.ac.tuwien.inso.eclipse.i18n.java/plugin.xml b/at.ac.tuwien.inso.eclipse.i18n.java/plugin.xml index abdbec6b..33585177 100644 --- a/at.ac.tuwien.inso.eclipse.i18n.java/plugin.xml +++ b/at.ac.tuwien.inso.eclipse.i18n.java/plugin.xml @@ -2,7 +2,7 @@ + point=""org.eclipselabs.tapiji.tools.core.builderExtension""> @@ -13,13 +13,13 @@ activate=""true"" class=""ui.ConstantStringHover"" description=""hovers constant strings"" - id=""at.ac.tuwien.inso.eclipse.i18n.ui.ConstantStringHover"" + id=""org.eclipselabs.tapiji.tools.java.ui.ConstantStringHover"" label=""Constant Strings""> getMarkerResolutions(IMarker marker, - int cause) { + public List getMarkerResolutions(IMarker marker) { List resolutions = new ArrayList(); - + int cause = marker.getAttribute(""cause"", -1); + switch (marker.getAttribute(""cause"", -1)) { case IMarkerConstants.CAUSE_CONSTANT_LITERAL: resolutions.add(new ExportToResourceBundleResolution()); diff --git a/at.ac.tuwien.inso.eclipse.i18n.java/src/auditor/ResourceAuditVisitor.java b/at.ac.tuwien.inso.eclipse.i18n.java/src/auditor/ResourceAuditVisitor.java index 4a22f0a5..74708c6b 100644 --- a/at.ac.tuwien.inso.eclipse.i18n.java/src/auditor/ResourceAuditVisitor.java +++ b/at.ac.tuwien.inso.eclipse.i18n.java/src/auditor/ResourceAuditVisitor.java @@ -24,9 +24,9 @@ import org.eclipse.jdt.core.dom.VariableDeclarationStatement; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Region; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; import util.ASTutils; -import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager; import auditor.model.SLLocation; /** diff --git a/at.ac.tuwien.inso.eclipse.i18n.java/src/auditor/model/SLLocation.java b/at.ac.tuwien.inso.eclipse.i18n.java/src/auditor/model/SLLocation.java index 97269552..3bfd8d28 100644 --- a/at.ac.tuwien.inso.eclipse.i18n.java/src/auditor/model/SLLocation.java +++ b/at.ac.tuwien.inso.eclipse.i18n.java/src/auditor/model/SLLocation.java @@ -3,8 +3,8 @@ import java.io.Serializable; import org.eclipse.core.resources.IFile; +import org.eclipselabs.tapiji.tools.core.extensions.ILocation; -import at.ac.tuwien.inso.eclipse.i18n.extensions.ILocation; public class SLLocation implements Serializable, ILocation { @@ -13,7 +13,7 @@ public class SLLocation implements Serializable, ILocation { private int startPos = -1; private int endPos = -1; private String literal; - private Object data; + private Serializable data; public SLLocation(IFile file, int startPos, int endPos, String literal) { super(); @@ -43,10 +43,10 @@ public void setEndPos(int endPos) { public String getLiteral() { return literal; } - public Object getData () { + public Serializable getData () { return data; } - public void setData (Object data) { + public void setData (Serializable data) { this.data = data; } diff --git a/at.ac.tuwien.inso.eclipse.i18n.java/src/quickfix/ExportToResourceBundleResolution.java b/at.ac.tuwien.inso.eclipse.i18n.java/src/quickfix/ExportToResourceBundleResolution.java index af0afc60..8757c86c 100644 --- a/at.ac.tuwien.inso.eclipse.i18n.java/src/quickfix/ExportToResourceBundleResolution.java +++ b/at.ac.tuwien.inso.eclipse.i18n.java/src/quickfix/ExportToResourceBundleResolution.java @@ -12,10 +12,10 @@ import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IMarkerResolution2; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; +import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog; import util.ASTutils; -import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager; -import at.ac.tuwien.inso.eclipse.i18n.ui.dialogs.CreateResourceBundleEntryDialog; public class ExportToResourceBundleResolution implements IMarkerResolution2 { diff --git a/at.ac.tuwien.inso.eclipse.i18n.java/src/quickfix/ReplaceResourceBundleDefReference.java b/at.ac.tuwien.inso.eclipse.i18n.java/src/quickfix/ReplaceResourceBundleDefReference.java index 58fefe76..8352326b 100644 --- a/at.ac.tuwien.inso.eclipse.i18n.java/src/quickfix/ReplaceResourceBundleDefReference.java +++ b/at.ac.tuwien.inso.eclipse.i18n.java/src/quickfix/ReplaceResourceBundleDefReference.java @@ -14,10 +14,10 @@ import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IMarkerResolution2; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; +import org.eclipselabs.tapiji.tools.core.ui.dialogs.InsertResourceBundleReferenceDialog; +import org.eclipselabs.tapiji.tools.core.ui.dialogs.ResourceBundleSelectionDialog; -import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager; -import at.ac.tuwien.inso.eclipse.i18n.ui.dialogs.InsertResourceBundleReferenceDialog; -import at.ac.tuwien.inso.eclipse.i18n.ui.dialogs.ResourceBundleSelectionDialog; public class ReplaceResourceBundleDefReference implements IMarkerResolution2 { diff --git a/at.ac.tuwien.inso.eclipse.i18n.java/src/quickfix/ReplaceResourceBundleReference.java b/at.ac.tuwien.inso.eclipse.i18n.java/src/quickfix/ReplaceResourceBundleReference.java index 7b18a4cb..3e92be00 100644 --- a/at.ac.tuwien.inso.eclipse.i18n.java/src/quickfix/ReplaceResourceBundleReference.java +++ b/at.ac.tuwien.inso.eclipse.i18n.java/src/quickfix/ReplaceResourceBundleReference.java @@ -14,9 +14,9 @@ import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IMarkerResolution2; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; +import org.eclipselabs.tapiji.tools.core.ui.dialogs.InsertResourceBundleReferenceDialog; -import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager; -import at.ac.tuwien.inso.eclipse.i18n.ui.dialogs.InsertResourceBundleReferenceDialog; public class ReplaceResourceBundleReference implements IMarkerResolution2 { diff --git a/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/ConstantStringHover.java b/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/ConstantStringHover.java index face8493..a0e12a53 100644 --- a/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/ConstantStringHover.java +++ b/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/ConstantStringHover.java @@ -9,8 +9,8 @@ import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.ui.IEditorPart; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; -import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager; import auditor.ResourceAuditVisitor; public class ConstantStringHover implements IJavaEditorTextHover { diff --git a/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/MessageCompletionProposalComputer.java b/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/MessageCompletionProposalComputer.java index 739cce7e..f6b77524 100644 --- a/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/MessageCompletionProposalComputer.java +++ b/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/MessageCompletionProposalComputer.java @@ -18,15 +18,15 @@ import org.eclipse.jdt.ui.text.java.JavaContentAssistInvocationContext; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.contentassist.ICompletionProposal; +import org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature; +import org.eclipselabs.tapiji.tools.core.builder.quickfix.CreateResourceBundle; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup; import ui.autocompletion.InsertResourceBundleReferenceProposal; import ui.autocompletion.MessageCompletionProposal; import ui.autocompletion.NewResourceBundleEntryProposal; import ui.autocompletion.NoActionProposal; -import at.ac.tuwien.inso.eclipse.i18n.builder.InternationalizationNature; -import at.ac.tuwien.inso.eclipse.i18n.builder.quickfix.CreateResourceBundle; -import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup; import auditor.ResourceAuditVisitor; public class MessageCompletionProposalComputer implements diff --git a/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/autocompletion/InsertResourceBundleReferenceProposal.java b/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/autocompletion/InsertResourceBundleReferenceProposal.java index 9193c764..0382ba19 100644 --- a/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/autocompletion/InsertResourceBundleReferenceProposal.java +++ b/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/autocompletion/InsertResourceBundleReferenceProposal.java @@ -13,10 +13,10 @@ import org.eclipse.swt.widgets.Display; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; +import org.eclipselabs.tapiji.tools.core.ui.dialogs.InsertResourceBundleReferenceDialog; import util.ASTutils; -import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager; -import at.ac.tuwien.inso.eclipse.i18n.ui.dialogs.InsertResourceBundleReferenceDialog; public class InsertResourceBundleReferenceProposal implements IJavaCompletionProposal { diff --git a/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/autocompletion/MessageCompletionProposal.java b/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/autocompletion/MessageCompletionProposal.java index d034358d..7c43856d 100644 --- a/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/autocompletion/MessageCompletionProposal.java +++ b/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/autocompletion/MessageCompletionProposal.java @@ -5,8 +5,8 @@ import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; +import org.eclipselabs.tapiji.tools.core.util.ImageUtils; -import at.ac.tuwien.inso.eclipse.i18n.util.ImageUtils; public class MessageCompletionProposal implements IJavaCompletionProposal { diff --git a/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/autocompletion/NewResourceBundleEntryProposal.java b/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/autocompletion/NewResourceBundleEntryProposal.java index 37261d98..7477d2d1 100644 --- a/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/autocompletion/NewResourceBundleEntryProposal.java +++ b/at.ac.tuwien.inso.eclipse.i18n.java/src/ui/autocompletion/NewResourceBundleEntryProposal.java @@ -10,10 +10,10 @@ import org.eclipse.swt.widgets.Display; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; +import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog; import util.ASTutils; -import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager; -import at.ac.tuwien.inso.eclipse.i18n.ui.dialogs.CreateResourceBundleEntryDialog; public class NewResourceBundleEntryProposal implements IJavaCompletionProposal {" e56f26140787fbe76b3c155c0248558287370e2c,Delta Spike,"DELTASPIKE-208 explicitely enable global alternatives This now works on Weld, OWB with BDA enabled, etc ",c,https://github.com/apache/deltaspike,"diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/exclude/extension/ExcludeExtension.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/exclude/extension/ExcludeExtension.java index 88a59724e..22dd33cb1 100644 --- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/exclude/extension/ExcludeExtension.java +++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/exclude/extension/ExcludeExtension.java @@ -44,8 +44,10 @@ import java.net.URL; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Manifest; @@ -60,27 +62,56 @@ */ public class ExcludeExtension implements Extension, Deactivatable { - private static final Logger LOG = Logger.getLogger(ExcludeExtension.class.getName()); + private static final String GLOBAL_ALTERNATIVES = ""globalAlternatives.""; - private static Boolean isWeld1Detected = false; + private static final Logger LOG = Logger.getLogger(ExcludeExtension.class.getName()); private boolean isActivated = true; private boolean isGlobalAlternativeActivated = true; private boolean isCustomProjectStageBeanFilterActivated = true; + /** + * Contains the globalAlternatives which should get used + * KEY=Interface class name + * VALUE=Implementation class name + */ + private Map globalAlternatives = new HashMap(); + + @SuppressWarnings(""UnusedDeclaration"") protected void init(@Observes BeforeBeanDiscovery beforeBeanDiscovery, BeanManager beanManager) { isActivated = ClassDeactivationUtils.isActivated(getClass()); - isGlobalAlternativeActivated = - ClassDeactivationUtils.isActivated(GlobalAlternative.class); - isCustomProjectStageBeanFilterActivated = ClassDeactivationUtils.isActivated(CustomProjectStageBeanFilter.class); - isWeld1Detected = isWeld1(beanManager); + isGlobalAlternativeActivated = + ClassDeactivationUtils.isActivated(GlobalAlternative.class); + if (isGlobalAlternativeActivated) + { + Map allProperties = ConfigResolver.getAllProperties(); + for (Map.Entry property : allProperties.entrySet()) + { + if (property.getKey().startsWith(GLOBAL_ALTERNATIVES)) + { + String interfaceName = property.getKey().substring(GLOBAL_ALTERNATIVES.length()); + String implementation = property.getValue(); + if (LOG.isLoggable(Level.FINE)) + { + LOG.fine(""Enabling global alternative for interface "" + interfaceName + "": "" + implementation); + } + + globalAlternatives.put(interfaceName, implementation); + } + } + + if (globalAlternatives.isEmpty()) + { + isGlobalAlternativeActivated = false; + } + } } /** @@ -101,9 +132,9 @@ protected void initProjectStage(@Observes AfterDeploymentValidation afterDeploym protected void vetoBeans(@Observes ProcessAnnotatedType processAnnotatedType, BeanManager beanManager) { //we need to do it before the exclude logic to keep the @Exclude support for global alternatives - if (isGlobalAlternativeActivated && isWeld1Detected) + if (isGlobalAlternativeActivated) { - activateGlobalAlternativesWeld1(processAnnotatedType, beanManager); + activateGlobalAlternatives(processAnnotatedType, beanManager); } if (isCustomProjectStageBeanFilterActivated) @@ -158,8 +189,8 @@ protected void vetoCustomProjectStageBeans(ProcessAnnotatedType processAnnotated - private void activateGlobalAlternativesWeld1(ProcessAnnotatedType processAnnotatedType, - BeanManager beanManager) + private void activateGlobalAlternatives(ProcessAnnotatedType processAnnotatedType, + BeanManager beanManager) { Class currentBean = processAnnotatedType.getAnnotatedType().getJavaClass(); @@ -184,7 +215,7 @@ private void activateGlobalAlternativesWeld1(ProcessAnnotatedType processAnnotat { alternativeBeanAnnotations = new HashSet(); - configuredBeanName = ConfigResolver.getPropertyValue(currentType.getName()); + configuredBeanName = globalAlternatives.get(currentType.getName()); if (configuredBeanName != null && configuredBeanName.length() > 0) { alternativeBeanClass = ClassUtils.tryToLoadClassForName(configuredBeanName); @@ -442,26 +473,6 @@ private void veto(ProcessAnnotatedType processAnnotatedType, String vetoType) processAnnotatedType.getAnnotatedType().getJavaClass()); } - private boolean isWeld1(BeanManager beanManager) - { - if (beanManager.getClass().getName().startsWith(""org.apache"")) - { - return false; - } - - if (beanManager.getClass().getName().startsWith(""org.jboss.weld"")) - { - String version = getJarVersion(beanManager.getClass()); - - if (version != null && version.startsWith(""1."")) - { - return true; - } - } - - return false; - } - private static String getJarVersion(Class targetClass) { String manifestFileLocation = getManifestFileLocationOfClass(targetClass); diff --git a/deltaspike/core/impl/src/test/resources/META-INF/apache-deltaspike.properties b/deltaspike/core/impl/src/test/resources/META-INF/apache-deltaspike.properties index b935ffcb8..ba2908684 100644 --- a/deltaspike/core/impl/src/test/resources/META-INF/apache-deltaspike.properties +++ b/deltaspike/core/impl/src/test/resources/META-INF/apache-deltaspike.properties @@ -20,10 +20,10 @@ org.apache.deltaspike.core.spi.activation.ClassDeactivator=org.apache.deltaspike testProperty02=test_value_02 db=prodDB -org.apache.deltaspike.test.core.api.alternative.global.BaseBean1=org.apache.deltaspike.test.core.api.alternative.global.SubBaseBean2 -org.apache.deltaspike.test.core.api.alternative.global.BaseInterface1=org.apache.deltaspike.test.core.api.alternative.global.BaseInterface1AlternativeImplementation +globalAlternatives.org.apache.deltaspike.test.core.api.alternative.global.BaseBean1=org.apache.deltaspike.test.core.api.alternative.global.SubBaseBean2 +globalAlternatives.org.apache.deltaspike.test.core.api.alternative.global.BaseInterface1=org.apache.deltaspike.test.core.api.alternative.global.BaseInterface1AlternativeImplementation -org.apache.deltaspike.test.core.api.alternative.global.qualifier.BaseInterface=org.apache.deltaspike.test.core.api.alternative.global.qualifier.AlternativeBaseBeanB +globalAlternatives.org.apache.deltaspike.test.core.api.alternative.global.qualifier.BaseInterface=org.apache.deltaspike.test.core.api.alternative.global.qualifier.AlternativeBaseBeanB configProperty1=14 configProperty2=7" c251c539b5e9aaf8b1e8f957254917c0b18e850d,apache$maven-plugins,"[MCHANGES-168]: Fix non-Latin-script character handling. The actual repair here was the change to maven-reporting-impl version 2.1. However, I then went off and set up a way to test JIRA functionality without actually talking to JIRA. That involved a bit of refactoring and mocking. git-svn-id: https://svn.apache.org/repos/asf/maven/plugins/trunk@1131489 13f79535-47bb-0310-9956-ffa450edef68 ",p,https://github.com/apache/maven-plugins,"diff --git a/maven-changes-plugin/pom.xml b/maven-changes-plugin/pom.xml index ed3fb521c4..08bec40dc7 100644 --- a/maven-changes-plugin/pom.xml +++ b/maven-changes-plugin/pom.xml @@ -122,7 +122,7 @@ under the License. org.apache.maven.reporting maven-reporting-impl - 2.0.5 + 2.1 org.apache.maven.shared diff --git a/maven-changes-plugin/src/main/java/org/apache/maven/plugin/changes/AbstractChangesReport.java b/maven-changes-plugin/src/main/java/org/apache/maven/plugin/changes/AbstractChangesReport.java index dfb64e2e32..234ebb8b66 100644 --- a/maven-changes-plugin/src/main/java/org/apache/maven/plugin/changes/AbstractChangesReport.java +++ b/maven-changes-plugin/src/main/java/org/apache/maven/plugin/changes/AbstractChangesReport.java @@ -174,7 +174,7 @@ public void execute() { DecorationModel model = new DecorationModel(); model.setBody( new Body() ); - Map attributes = new HashMap(); + Map attributes = new HashMap(); attributes.put( ""outputEncoding"", getOutputEncoding() ); Locale locale = Locale.getDefault(); SiteRenderingContext siteContext = siteRenderer.createContextForSkin( getSkinArtifactFile(), attributes, diff --git a/maven-changes-plugin/src/main/java/org/apache/maven/plugin/jira/AbstractJiraDownloader.java b/maven-changes-plugin/src/main/java/org/apache/maven/plugin/jira/AbstractJiraDownloader.java index 777c3e430c..1063044f6a 100644 --- a/maven-changes-plugin/src/main/java/org/apache/maven/plugin/jira/AbstractJiraDownloader.java +++ b/maven-changes-plugin/src/main/java/org/apache/maven/plugin/jira/AbstractJiraDownloader.java @@ -69,7 +69,7 @@ public abstract class AbstractJiraDownloader private static final String UTF_8 = ""UTF-8""; /** Log for debug output. */ - private Log log; + protected Log log; /** Output file for xml document. */ private File output; /** The maximum number of entries to show. */ @@ -111,7 +111,7 @@ public abstract class AbstractJiraDownloader /** Mapping containing all allowed JIRA type values. */ protected final Map typeMap = new HashMap( 8 ); /** The pattern used to parse dates from the JIRA xml file. */ - private String jiraDatePattern; + protected String jiraDatePattern; /** * Creates a filter given the parameters and some defaults. @@ -421,7 +421,12 @@ public void doExecute() } catch ( Exception e ) { - getLog().error( ""Error accessing "" + project.getIssueManagement().getUrl(), e ); + if ( project.getIssueManagement() != null) + { + getLog().error( ""Error accessing "" + project.getIssueManagement().getUrl(), e ); + } else { + getLog().error( ""Error accessing mock project issues"", e ); + } } } diff --git a/maven-changes-plugin/src/main/java/org/apache/maven/plugin/jira/JiraMojo.java b/maven-changes-plugin/src/main/java/org/apache/maven/plugin/jira/JiraMojo.java index 4e31627fdd..3b677b415d 100644 --- a/maven-changes-plugin/src/main/java/org/apache/maven/plugin/jira/JiraMojo.java +++ b/maven-changes-plugin/src/main/java/org/apache/maven/plugin/jira/JiraMojo.java @@ -295,6 +295,11 @@ public class JiraMojo * @parameter default-value="""" */ private String webUser; + + /* + * Used for tests. + */ + private AbstractJiraDownloader mockDownloader; /* --------------------------------------------------------------------- */ /* Public methods */ @@ -305,6 +310,10 @@ public class JiraMojo */ public boolean canGenerateReport() { + if ( mockDownloader != null) + { + return true; + } return ProjectUtils.validateIfIssueManagementComplete( project, ""JIRA"", ""JIRA Report"", getLog() ); } @@ -323,7 +332,13 @@ public void executeReport( Locale locale ) try { // Download issues - JiraDownloader issueDownloader = new JiraDownloader(); + AbstractJiraDownloader issueDownloader; + if ( mockDownloader != null) + { + issueDownloader = mockDownloader; + } else { + issueDownloader = new JiraDownloader(); + } configureIssueDownloader( issueDownloader ); issueDownloader.doExecute(); @@ -386,7 +401,7 @@ private ResourceBundle getBundle( Locale locale ) return ResourceBundle.getBundle( ""jira-report"", locale, this.getClass().getClassLoader() ); } - private void configureIssueDownloader( JiraDownloader issueDownloader ) + private void configureIssueDownloader( AbstractJiraDownloader issueDownloader ) { issueDownloader.setLog( getLog() ); @@ -424,4 +439,14 @@ private void configureIssueDownloader( JiraDownloader issueDownloader ) issueDownloader.setSettings( settings ); } + + public void setMockDownloader( AbstractJiraDownloader mockDownloader ) + { + this.mockDownloader = mockDownloader; + } + + public AbstractJiraDownloader getMockDownloader() + { + return mockDownloader; + } } diff --git a/maven-changes-plugin/src/main/java/org/apache/maven/plugin/jira/JiraXML.java b/maven-changes-plugin/src/main/java/org/apache/maven/plugin/jira/JiraXML.java index 3f03363212..0e4ce55487 100644 --- a/maven-changes-plugin/src/main/java/org/apache/maven/plugin/jira/JiraXML.java +++ b/maven-changes-plugin/src/main/java/org/apache/maven/plugin/jira/JiraXML.java @@ -20,6 +20,8 @@ */ import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -34,14 +36,14 @@ import org.apache.maven.plugin.issues.Issue; import org.apache.maven.plugin.logging.Log; import org.xml.sax.Attributes; +import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** - * XML parser that extracts Issues from JIRA. This works on an XML - * file downloaded from JIRA and creates a List of issues that is - * exposed to the user of the class. - * + * XML parser that extracts Issues from JIRA. This works on an XML file downloaded from JIRA and creates a + * List of issues that is exposed to the user of the class. + * * @version $Id$ */ public class JiraXML @@ -64,7 +66,6 @@ public class JiraXML private SimpleDateFormat sdf = null; /** - * * @param log not null. * @param datePattern may be null. * @since 2.4 @@ -89,29 +90,49 @@ public JiraXML( Log log, String datePattern ) /** * Parse the given xml file. The list of issues can then be retrieved with {@link #getIssueList()}. - * + * * @param xmlPath the file to pares. - * @throws MojoExecutionException - * + * @throws MojoExecutionException * @since 2.4 */ - public void parseXML( File xmlPath ) throws MojoExecutionException + public void parseXML( File xmlPath ) + throws MojoExecutionException { - parse( xmlPath ); + FileInputStream xmlStream = null; + try + { + InputSource inputSource = new InputSource( xmlStream ); + parse( inputSource ); + } + finally + { + if ( xmlStream != null ) + { + try + { + xmlStream.close(); + } + catch ( IOException e ) + { + // + } + } + } } - private void parse( File xmlPath ) throws MojoExecutionException + void parse( InputSource xmlSource ) + throws MojoExecutionException { try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); - saxParser.parse( xmlPath, this ); + saxParser.parse( xmlSource, this ); } catch ( Throwable t ) { - throw new MojoExecutionException ( ""Failed to parse JIRA XML."", t ); + throw new MojoExecutionException( ""Failed to parse JIRA XML."", t ); } } diff --git a/maven-changes-plugin/src/test/java/org/apache/maven/plugin/jira/JiraUnicodeTestCase.java b/maven-changes-plugin/src/test/java/org/apache/maven/plugin/jira/JiraUnicodeTestCase.java new file mode 100644 index 0000000000..113b1af698 --- /dev/null +++ b/maven-changes-plugin/src/test/java/org/apache/maven/plugin/jira/JiraUnicodeTestCase.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.maven.plugin.jira; + +import java.io.File; +import java.io.InputStream; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.maven.plugin.testing.AbstractMojoTestCase; + +/** + * + */ +public class JiraUnicodeTestCase extends AbstractMojoTestCase +{ + /* + * Something in Doxia escapes all non-Ascii even when the charset is UTF-8. + * This test will fail if that ever changes. + */ + private final static String TEST_TURTLES = ""海龟一路下跌。""; + public void testUnicodeReport() throws Exception { + + File pom = new File( getBasedir(), ""/src/test/unit/jira-plugin-config.xml"" ); + assertNotNull( pom ); + assertTrue( pom.exists() ); + + JiraMojo mojo = (JiraMojo) lookupMojo( ""jira-report"", pom ); + InputStream testJiraXmlStream = JiraUnicodeTestCase.class.getResourceAsStream( ""unicode-jira-results.xml"" ); + String jiraXml = IOUtils.toString( testJiraXmlStream, ""utf-8"" ); + MockJiraDownloader mockDownloader = new MockJiraDownloader(); + mockDownloader.setJiraXml( jiraXml ); + mojo.setMockDownloader( mockDownloader ); + File outputDir = new File ( ""target/jira-test-output"" ); + outputDir.mkdirs(); + mojo.setReportOutputDirectory( outputDir ); + mojo.execute(); + String reportHtml = FileUtils.readFileToString( new File( outputDir, ""jira-report.html"" ), + ""utf-8"" ); + int turtleIndex = reportHtml.indexOf( TEST_TURTLES ); + assertTrue ( turtleIndex >= 0 ); + } + +} diff --git a/maven-changes-plugin/src/test/java/org/apache/maven/plugin/jira/JiraUnicodeTestProjectStub.java b/maven-changes-plugin/src/test/java/org/apache/maven/plugin/jira/JiraUnicodeTestProjectStub.java new file mode 100644 index 0000000000..7937bd7ac6 --- /dev/null +++ b/maven-changes-plugin/src/test/java/org/apache/maven/plugin/jira/JiraUnicodeTestProjectStub.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugin.jira; + +import java.util.Collections; +import java.util.List; + +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.repository.DefaultArtifactRepository; +import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + */ +public class JiraUnicodeTestProjectStub + extends MavenProjectStub +{ + + /** {@inheritDoc} */ + @Override + public List getRemoteArtifactRepositories() + { + ArtifactRepository repository = new DefaultArtifactRepository( ""central"", ""http://repo1.maven.org/maven2"", + new DefaultRepositoryLayout() ); + + return Collections.singletonList( repository ); + } + +} diff --git a/maven-changes-plugin/src/test/java/org/apache/maven/plugin/jira/MockJiraDownloader.java b/maven-changes-plugin/src/test/java/org/apache/maven/plugin/jira/MockJiraDownloader.java new file mode 100644 index 0000000000..02d27d8ae4 --- /dev/null +++ b/maven-changes-plugin/src/test/java/org/apache/maven/plugin/jira/MockJiraDownloader.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.maven.plugin.jira; + +import java.io.StringReader; +import java.util.List; + +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.issues.Issue; +import org.xml.sax.InputSource; + +/** + * Allow test cases in the jira mojo without actually talking to jira. + * + */ +public class MockJiraDownloader extends AbstractJiraDownloader +{ + @Override + public void doExecute() + throws Exception + { + // do nothing + } + + private String jiraXml; + @Override + public List getIssueList() + throws MojoExecutionException + { + JiraXML jira = new JiraXML( log, jiraDatePattern ); + InputSource inputSource = new InputSource ( new StringReader( jiraXml )); + jira.parse( inputSource ); + log.info( ""The JIRA version is '"" + jira.getJiraVersion() + ""'"" ); + return jira.getIssueList(); + } + + public void setJiraXml( String jiraXml ) + { + this.jiraXml = jiraXml; + } + + public String getJiraXml() + { + return jiraXml; + } + +} diff --git a/maven-changes-plugin/src/test/resources/org/apache/maven/plugin/jira/unicode-jira-results.xml b/maven-changes-plugin/src/test/resources/org/apache/maven/plugin/jira/unicode-jira-results.xml new file mode 100644 index 0000000000..00b337c77e --- /dev/null +++ b/maven-changes-plugin/src/test/resources/org/apache/maven/plugin/jira/unicode-jira-results.xml @@ -0,0 +1,309 @@ + + + + + Professional Computer Services S.A. JIRA + http://pcsjira.slg.gr/secure/IssueNavigator.jspa?reset=true&pid=10101&status=6&resolution=1&sorter/field=created&sorter/order=DESC&sorter/field=priority&sorter/order=DESC + An XML representation of a search request + en-us + 3.13.2 + 335 + 26-11-2008 + Enterprise + + + +[PCSUNIT-2] 海龟一路下跌。 Απεικόνιση σε EXCEL των data των φορμών. Περίπτωση με πολλά blocks +http://pcsjira.slg.gr/browse/PCSUNIT-2 + + + + PCSUNIT-2 + 海龟一路下跌。 Απεικόνιση σε EXCEL των data των φορμών. Περίπτωση με πολλά blocks + + Improvement + + + Normal + Closed + Fixed + + Internal Issue + + Nikolaos Stais + + Nikolaos Stais + + Wed, 18 Mar 2009 11:04:28 +0200 (EET) + Thu, 23 Apr 2009 13:22:19 +0300 (EEST) + + + + + + + 0 + + + + + Εχει πραγματοποιηθεί μια πρώτη προσέγγιση κ υλοποίηση, χρειάζεται ΤΕΣΤ + + + + + + + + + + + Α/Η + + 2.0 + + + + + + + +[PCSUNIT-1] ΔΗΜΙΟΥΡΓΙΑ ΔΙΑΔΙΚΑΣΙΑΣ ΓΙΑ UNDO CHANGES +http://pcsjira.slg.gr/browse/PCSUNIT-1 + + + + PCSUNIT-1 + ΔΗΜΙΟΥΡΓΙΑ ΔΙΑΔΙΚΑΣΙΑΣ ΓΙΑ UNDO CHANGES + + New Feature + + + Minor + Closed + Fixed + + Internal Issue + + Nikolaos Stais + + Nikolaos Stais + + Wed, 4 Feb 2009 13:47:25 +0200 (EET) + Wed, 13 May 2009 13:32:49 +0300 (EEST) + + + + + + + 0 + + + + + Έγινε μια πρώτη προσέγγιση και ενημέρωση συναδέλφων. Σε αναμονή δοκιμής από τους ενδιαφερόμενους. + &nbsp; +<br/> + +<br/> +Έχοντας λάβει κάποια requests από πελάτες οι οποίοι επιθυμούν να κάνουν undo σε batch ροές, +<br/> + +<br/> +θεωρώ ότι υπάρχει ένας εύκολος τρόπος να το πετύχουμε, προκειμένου να αποφύγουμε να κρατάμε ιστορικότητα στις αλλαγές (που έως τώρα θα κάναμε commit). +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +Το συγκεκριμένο θέμα δεν έχει εφαρμοστεί (από όσο ξέρω) με τρόπο που να εισάγουμε δεδομένα και να τα δείχνουμε χωρίς να έχουν γίνει commit. +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +Τολμώ να κάνω μια πρόταση προς διερεύνηση ... J +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +Θεωρητικά θα μπορούμε π.χ. να κάνουμε ενημέρωση με τιμή να βλέπουμε τι μερίδια έχουν κοπεί (καλώντας την inv3) και μετά αν δε πατάμε το οριστικό commit button, βγαίνοντας από την +<br/> + +<br/> +οθόνη θα είναι σαν να μην έχουμε κάνει τίποτα. +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +Η όλη δουλεία γίνεται με αλλαγές στα εξής σημεία. +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +Στον ON-COMMIT trigger (form-level). +<br/> + +<br/> +Στον ΚΕΥ-COMMIT trigger (form-level) +<br/> + +<br/> +Στον KEY-EXIT trigger (form-level) +<br/> + +<br/> +Στον KEY-ENTQRY trigger (form-level) +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +Οπωσδήποτε αν υπάρχουν αντίστοιχοι triggers σε block-level, τότε πρέπει να επεξεργαστούν κατάλληλα. +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +Στην ουσία, δεν κάνουμε ποτέ commit (αλλά POST;?στέλνει τα records στη βάση), παρά μόνο πατώντας το κουμπί REAL COMMIT. +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +Μπορείτε να δείτε τα form1.fmb , form2.fmb που υπάρχουν στο Y:\MFHELLAS_10G\Exedir +<br/> + +<br/> +ή και να τεστάρετε το εξής σενάριο(<a href="http://dioskouros:7778/forms90/f90servlet?config=test_undo">http://dioskouros:7778/forms90/f90servlet?config=test_undo</a>) +<br/> + +<br/> +στην πράξη: +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +Η form1 βλέπει ένα απλό πίνακα με 2 στήλες. Κάθε φορά που εισάγω μια εγγραφή και πατάω F10 βλέπω μήνυμα +<br/> + +<br/> +&quot;1 record applied&quot; (η διαφορά φαίνεται κ εδώ, δηλ. δεν λέει: &quot;1 record applied and saved&quot;, λείπει το &quot;saved&quot;=δεν έχει κάνει commit στη βάση αλλά έχει στείλει τα record στη βάση για να μπορούν άλλες οθόνες να τα κάνουν query.) +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +Αν καλέσουμε τη δεύτερη οθόνη form2, μπορούμε να κάνουμε query τις αλλαγές(insert,delete,update + F10) που πραγματοποιήσαμε στην οθόνη form1. +<br/> + +<br/> +Αν στην ίδια οθόνη (form1) κάνουμε F7 χωρίς να κάνουμε F10 (μετά την αλλαγή) η οθόνη χάνει τις αλλαγές (προγραμματιστικά επίτηδες, προς αποφυγή της ερώτησης save changes?) +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +Βγαίνοντας από τις δύο οθόνες χωρίς να πατήσουμε το button REAL COMMIT, όλες οι αλλαγές που κάναμε στην form1 και τις είδαμε στη 2η οθόνη form2 δεν έχουν σωθεί. +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +Τα insert, update, delete μπορούν να γίνουν και προγραμματιστικά. Στην οθόνη form1 στον ON-INSERT trigger του block, υπάρχει για λόγους τεστ ένα insert, το οποίο λειτουργεί με κάθε νέα εγγραφή. +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +Παρακαλώ για τα σχόλια σας και ιδιαίτερα για τους ενδεχόμενους κινδύνους, αν σας το επιτρέπει ο χρόνος σας. +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +&nbsp; +<br/> + +<br/> +Ευχαριστώ πολύ, +<br/> + +<br/> + + + + + + + + + + + + Screen Code + + ΘΕΩΡΙΤΙΚ Α ΕΦΑΡΜΟΓΗ ΣΕ ΟΛΕΣ ΤΙΣ ΟΘΟΝΕΣ + + + + + + + + diff --git a/maven-changes-plugin/src/test/unit/jira-plugin-config.xml b/maven-changes-plugin/src/test/unit/jira-plugin-config.xml new file mode 100644 index 0000000000..faec73ef18 --- /dev/null +++ b/maven-changes-plugin/src/test/unit/jira-plugin-config.xml @@ -0,0 +1,36 @@ + + + + + changes-plugin-test + + + + maven-changes-plugin + + ${localRepository} + + target/jira-test-output + Key,Summary,Status,Resolution,Assignee,Description + + + + +" 541aae12ef82767479bcd53afb3681b46dd890a5,spring-framework,SPR-5802 - NullPointerException when using- @CookieValue annotation--,c,https://github.com/spring-projects/spring-framework,"diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java index f6b7c4204360..e8fa23d6ac5f 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java @@ -600,9 +600,12 @@ protected Object resolveCookieValue(String cookieName, Class paramType, NativeWe if (Cookie.class.isAssignableFrom(paramType)) { return cookieValue; } - else { + else if (cookieValue != null) { return cookieValue.getValue(); } + else { + return null; + } } @Override" 4f79b07e174ed1f57115a6b0a9f6a6e74e6733ee,hadoop,HADOOP-6932. Namenode start (init) fails because- of invalid kerberos key,c,https://github.com/apache/hadoop,"diff --git a/CHANGES.txt b/CHANGES.txt index f43935c87233a..72a1e3e6ffa26 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -220,6 +220,9 @@ Trunk (unreleased changes) HADOOP-6833. IPC leaks call parameters when exceptions thrown. (Todd Lipcon via Eli Collins) + HADOOP-6932. Namenode start (init) fails because of invalid kerberos + key, even when security set to ""simple"" (boryas) + Release 0.21.0 - Unreleased INCOMPATIBLE CHANGES diff --git a/src/java/org/apache/hadoop/security/SecurityUtil.java b/src/java/org/apache/hadoop/security/SecurityUtil.java index 00187bd6f2401..44ef31ef32989 100644 --- a/src/java/org/apache/hadoop/security/SecurityUtil.java +++ b/src/java/org/apache/hadoop/security/SecurityUtil.java @@ -174,7 +174,7 @@ static String getLocalHostName() throws UnknownHostException { } /** - * If a keytab has been provided, login as that user. Substitute $host in + * Login as a principal specified in config. Substitute $host in * user's Kerberos principal name with a dynamically looked-up fully-qualified * domain name of the current host. * @@ -192,8 +192,9 @@ public static void login(final Configuration conf, } /** - * If a keytab has been provided, login as that user. Substitute $host in - * user's Kerberos principal name with hostname. + * Login as a principal specified in config. Substitute $host in user's Kerberos principal + * name with hostname. If non-secure mode - return. If no keytab available - + * bail out with an exception * * @param conf * conf to use @@ -208,9 +209,14 @@ public static void login(final Configuration conf, public static void login(final Configuration conf, final String keytabFileKey, final String userNameKey, String hostname) throws IOException { - String keytabFilename = conf.get(keytabFileKey); - if (keytabFilename == null) + + if(! UserGroupInformation.isSecurityEnabled()) return; + + String keytabFilename = conf.get(keytabFileKey); + if (keytabFilename == null || keytabFilename.length() == 0) { + throw new IOException(""Running in secure mode, but config doesn't have a keytab""); + } String principalConfig = conf.get(userNameKey, System .getProperty(""user.name"")); diff --git a/src/test/core/org/apache/hadoop/security/TestSecurityUtil.java b/src/test/core/org/apache/hadoop/security/TestSecurityUtil.java index 14ec74372d091..d5a3a25f90972 100644 --- a/src/test/core/org/apache/hadoop/security/TestSecurityUtil.java +++ b/src/test/core/org/apache/hadoop/security/TestSecurityUtil.java @@ -16,12 +16,15 @@ */ package org.apache.hadoop.security; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.io.IOException; import javax.security.auth.kerberos.KerberosPrincipal; +import org.apache.hadoop.conf.Configuration; +import org.junit.Assert; import org.junit.Test; public class TestSecurityUtil { @@ -70,4 +73,23 @@ public void testGetServerPrincipal() throws IOException { verify(shouldNotReplace, hostname, shouldNotReplace); verify(shouldNotReplace, shouldNotReplace, shouldNotReplace); } + + @Test + public void testStartsWithIncorrectSettings() throws IOException { + Configuration conf = new Configuration(); + conf.set( + org.apache.hadoop.fs.CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION, + ""kerberos""); + String keyTabKey=""key""; + conf.set(keyTabKey, """"); + UserGroupInformation.setConfiguration(conf); + boolean gotException = false; + try { + SecurityUtil.login(conf, keyTabKey, """", """"); + } catch (IOException e) { + // expected + gotException=true; + } + assertTrue(""Exception for empty keytabfile name was expected"", gotException); + } }" 70d5d2c168bd477e3b8330fd7802b280d1f72b8e,camel,Set the isCreateCamelContextPerClass on tests- that can pass with it to speed up the tests--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1152396 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/camel,"diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/AbstractCXFGreeterRouterTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/AbstractCXFGreeterRouterTest.java index 54b4ae4946afe..0e1c4525d2cfc 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/AbstractCXFGreeterRouterTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/AbstractCXFGreeterRouterTest.java @@ -58,7 +58,6 @@ public static int getPort2() { return CXFTestSupport.getPort2(); } - protected abstract ClassPathXmlApplicationContext createApplicationContext(); @Before diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/AbstractCxfWsdlFirstTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/AbstractCxfWsdlFirstTest.java index 5c897860f286e..6bbf10faf28e6 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/AbstractCxfWsdlFirstTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/AbstractCxfWsdlFirstTest.java @@ -50,6 +50,10 @@ public static int getPort2() { return CXFTestSupport.getPort2(); } + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } @Test public void testInvokingServiceFromCXFClient() throws Exception { diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyPayloadModeMultiPartNoSpringTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyPayloadModeMultiPartNoSpringTest.java index b514ad825954d..ded24d8c76247 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyPayloadModeMultiPartNoSpringTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyPayloadModeMultiPartNoSpringTest.java @@ -48,6 +48,11 @@ public class CXFWsdlOnlyPayloadModeMultiPartNoSpringTest extends CamelTestSuppor + ""/CXFWsdlOnlyPayloadModeMultiPartNoSpringTest/PersonMultiPart""; protected Endpoint endpoint; + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } + @Before public void startService() { endpoint = Endpoint.publish(SERVICE_ADDRESS, new PersonMultiPartImpl()); diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyPayloadModeNoSpringSoap12Test.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyPayloadModeNoSpringSoap12Test.java index d89d35da58aa0..c70f8b6cf0f00 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyPayloadModeNoSpringSoap12Test.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyPayloadModeNoSpringSoap12Test.java @@ -25,7 +25,11 @@ public class CXFWsdlOnlyPayloadModeNoSpringSoap12Test extends CXFWsdlOnlyPayloadModeNoSpringTest { - + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } + @Before public void startService() { endpoint = Endpoint.publish(""http://localhost:"" + port1 + ""/"" diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyPayloadModeNoSpringTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyPayloadModeNoSpringTest.java index 0e785aa9f3d74..80cb403d02d21 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyPayloadModeNoSpringTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyPayloadModeNoSpringTest.java @@ -52,6 +52,11 @@ public class CXFWsdlOnlyPayloadModeNoSpringTest extends CamelTestSupport { protected int port1 = CXFTestSupport.getPort1(); protected int port2 = CXFTestSupport.getPort2(); + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } + @Before public void startService() { endpoint = Endpoint.publish(""http://localhost:"" + port1 + ""/"" + getClass().getSimpleName() diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyTest.java index 5f4730a2ffdb7..e1060f17c7daf 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyTest.java @@ -45,6 +45,9 @@ public class CXFWsdlOnlyTest extends CamelSpringTestSupport { private static int port3 = CXFTestSupport.getPort3(); private static int port4 = CXFTestSupport.getPort4(); + public boolean isCreateCamelContextPerClass() { + return true; + } protected ClassPathXmlApplicationContext createApplicationContext() { System.setProperty(""CXFWsdlOnlyTest.port1"", Integer.toString(port1)); diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerMessageTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerMessageTest.java index b21895182a9f0..bf8a8012d4590 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerMessageTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerMessageTest.java @@ -47,6 +47,10 @@ public class CxfConsumerMessageTest extends CamelTestSupport { protected final String simpleEndpointURI = ""cxf://"" + simpleEndpointAddress + ""?serviceClass=org.apache.camel.component.cxf.HelloService""; + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerPayloadFaultTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerPayloadFaultTest.java index 8686abb06e8ac..b1fdb15996919 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerPayloadFaultTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerPayloadFaultTest.java @@ -65,6 +65,10 @@ public class CxfConsumerPayloadFaultTest extends CamelTestSupport { protected final String fromURI = ""cxf://"" + serviceAddress + ""?"" + PORT_NAME_PROP + ""&"" + SERVICE_NAME_PROP + ""&"" + WSDL_URL_PROP + ""&dataFormat="" + DataFormat.PAYLOAD; + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerProviderTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerProviderTest.java index 76e6eaa11be83..64a932d1f28ea 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerProviderTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerProviderTest.java @@ -49,6 +49,10 @@ public class CxfConsumerProviderTest extends CamelTestSupport { + ""?serviceClass=org.apache.camel.component.cxf.ServiceProvider""; + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerResponseTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerResponseTest.java index 293957ccce39e..7b89881c07e20 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerResponseTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerResponseTest.java @@ -53,6 +53,10 @@ public class CxfConsumerResponseTest extends CamelTestSupport { + ""&publishedEndpointUrl=http://www.simple.com/services/test""; + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } // START SNIPPET: example protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerTest.java index d87323e65e403..e096593b142a5 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerTest.java @@ -51,7 +51,12 @@ public class CxfConsumerTest extends CamelTestSupport { private static final String ECHO_OPERATION = ""echo""; private static final String ECHO_BOOLEAN_OPERATION = ""echoBoolean""; private static final String TEST_MESSAGE = ""Hello World!""; - + + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } + // START SNIPPET: example protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfCustomerStartStopTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfCustomerStartStopTest.java index 66986987d7dbd..25543fb4a9d3e 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfCustomerStartStopTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfCustomerStartStopTest.java @@ -32,7 +32,10 @@ @org.junit.Ignore public class CxfCustomerStartStopTest extends Assert { static final int PORT1 = CXFTestSupport.getPort1(); - static final int PORT2 = CXFTestSupport.getPort1(); + static final int PORT2 = CXFTestSupport.getPort1(); + + + @Test public void startAndStopService() throws Exception { CamelContext context = new DefaultCamelContext(); diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfCustomizedExceptionTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfCustomizedExceptionTest.java index 3d32fc1c8d2a7..e67a734070d7f 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfCustomizedExceptionTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfCustomizedExceptionTest.java @@ -69,6 +69,10 @@ public class CxfCustomizedExceptionTest extends CamelTestSupport { private Bus bus; + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } @Override @Before diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfDispatchTestSupport.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfDispatchTestSupport.java index cf85aa427887f..7812026967f45 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfDispatchTestSupport.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfDispatchTestSupport.java @@ -52,6 +52,10 @@ public abstract class CxfDispatchTestSupport extends CamelSpringTestSupport { protected Endpoint endpoint; private int port = CXFTestSupport.getPort1(); + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } @Before public void startService() { diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfJavaOnlyPayloadModeTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfJavaOnlyPayloadModeTest.java index 4b72cd6993c2b..b9e92eb47bf65 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfJavaOnlyPayloadModeTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfJavaOnlyPayloadModeTest.java @@ -39,6 +39,10 @@ public class CxfJavaOnlyPayloadModeTest extends CamelTestSupport { + ""&portName={http://camel.apache.org/wsdl-first}soap"" + ""&dataFormat=PAYLOAD"" + ""&properties.exceptionMessageCauseEnabled=true&properties.faultStackTraceEnabled=true""; + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } @Test public void testCxfJavaOnly() throws Exception { diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfMixedModeRouterTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfMixedModeRouterTest.java index 9dce087c756a9..906cc0f4de7fb 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfMixedModeRouterTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfMixedModeRouterTest.java @@ -52,7 +52,11 @@ public class CxfMixedModeRouterTest extends CamelTestSupport { private String routerEndpointURI = ""cxf://"" + ROUTER_ADDRESS + ""?"" + SERVICE_CLASS + ""&dataFormat=PAYLOAD""; private String serviceEndpointURI = ""cxf://"" + SERVICE_ADDRESS + ""?"" + SERVICE_CLASS + ""&dataFormat=POJO""; - + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } + @BeforeClass public static void startService() { //start a service diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfNonWrapperTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfNonWrapperTest.java index ef033e3a5616a..74c02d60e155a 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfNonWrapperTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfNonWrapperTest.java @@ -34,7 +34,11 @@ public class CxfNonWrapperTest extends CamelSpringTestSupport { int port1 = CXFTestSupport.getPort1(); - + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } + protected ClassPathXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext(""org/apache/camel/component/cxf/nonWrapperProcessor.xml""); } diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfPayLoadSoapHeaderTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfPayLoadSoapHeaderTest.java index 073deff09346b..c95d33741dbc8 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfPayLoadSoapHeaderTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfPayLoadSoapHeaderTest.java @@ -56,7 +56,11 @@ protected String getServiceEndpointURI() { return ""cxf:http://localhost:"" + port2 + ""/"" + getClass().getSimpleName() + ""/new_pizza_service/services/PizzaService?wsdlURL=classpath:pizza_service.wsdl&dataFormat=PAYLOAD""; } - + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } + @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerProtocalHeaderTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerProtocalHeaderTest.java index c48127dc68af9..257ca29af2856 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerProtocalHeaderTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerProtocalHeaderTest.java @@ -38,6 +38,11 @@ public class CxfProducerProtocalHeaderTest extends CamelTestSupport { + ""echo Hello World!"" + """"; + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } + protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerRouterTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerRouterTest.java index 10727974f50cc..f0db44c96dc09 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerRouterTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerRouterTest.java @@ -51,6 +51,10 @@ public class CxfProducerRouterTest extends CamelTestSupport { private static final String ECHO_OPERATION = ""echo""; private static final String TEST_MESSAGE = ""Hello World!""; + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } @BeforeClass public static void startServer() throws Exception { diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerSynchronousFalseTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerSynchronousFalseTest.java index 074b7dd967e7a..28633d96e1322 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerSynchronousFalseTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerSynchronousFalseTest.java @@ -40,6 +40,10 @@ public class CxfProducerSynchronousFalseTest extends CamelTestSupport { private String url = ""cxf://"" + SIMPLE_SERVER_ADDRESS + ""?serviceClass=org.apache.camel.component.cxf.HelloService&dataFormat=MESSAGE&synchronous=false""; + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } @BeforeClass public static void startServer() throws Exception { diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerSynchronousTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerSynchronousTest.java index e15338b2966ab..6f9760d4b3285 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerSynchronousTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerSynchronousTest.java @@ -39,6 +39,10 @@ public class CxfProducerSynchronousTest extends CamelTestSupport { private String url = ""cxf://"" + SIMPLE_SERVER_ADDRESS + ""?serviceClass=org.apache.camel.component.cxf.HelloService&dataFormat=MESSAGE&synchronous=true""; + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } @BeforeClass public static void startServer() throws Exception { diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerTest.java index 7f5f0652ec96d..76da36e080567 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfProducerTest.java @@ -67,7 +67,6 @@ protected String getWrongServerAddress() { return ""http://localhost:"" + CXFTestSupport.getPort3() + ""/"" + getClass().getSimpleName() + ""/test""; } - @Before public void startService() throws Exception { // start a simple front service diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfRawMessageRouterTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfRawMessageRouterTest.java index 40cb2d44f3443..9a21fa8c98de4 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfRawMessageRouterTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfRawMessageRouterTest.java @@ -36,7 +36,11 @@ public void configure() { } }; } - + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } + @Test public void testTheContentType() throws Exception { MockEndpoint result = getMockEndpoint(""mock:result""); diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfSimpleRouterTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfSimpleRouterTest.java index c9cad6c10711b..c8fae21f095fb 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfSimpleRouterTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfSimpleRouterTest.java @@ -51,7 +51,11 @@ protected String getServiceAddress() { protected void configureFactory(ServerFactoryBean svrBean) { } - + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } + @Before public void startService() { //start a service diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfSoapMessageProviderTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfSoapMessageProviderTest.java index 4049f62f3ff1a..0b53668bea282 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfSoapMessageProviderTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfSoapMessageProviderTest.java @@ -38,6 +38,10 @@ public class CxfSoapMessageProviderTest extends CamelSpringTestSupport { protected ClassPathXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext(""org/apache/camel/component/cxf/SoapMessageProviderContext.xml""); } + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } @Test public void testSOAPMessageModeDocLit() throws Exception { diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfSpringCustomizedExceptionTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfSpringCustomizedExceptionTest.java index a39274bfe0406..c6e57a5e41403 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfSpringCustomizedExceptionTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfSpringCustomizedExceptionTest.java @@ -49,7 +49,11 @@ public class CxfSpringCustomizedExceptionTest extends CamelTestSupport { // END SNIPPET: FaultDefine } - + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } + @Before public void setUp() throws Exception { CXFTestSupport.getPort1(); diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfTimeoutTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfTimeoutTest.java index 8971deca12021..f57ded3e6427b 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfTimeoutTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfTimeoutTest.java @@ -39,6 +39,11 @@ public class CxfTimeoutTest extends CamelSpringTestSupport { protected static final String JAXWS_SERVER_ADDRESS = ""http://localhost:"" + CXFTestSupport.getPort1() + ""/CxfTimeoutTest/SoapContext/SoapPort""; + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } + @BeforeClass public static void startService() { Greeter implementor = new GreeterImplWithSleep(); diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstPayloadModeTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstPayloadModeTest.java index 764040443f881..cb1ee7710a9d8 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstPayloadModeTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstPayloadModeTest.java @@ -34,6 +34,10 @@ public class CxfWsdlFirstPayloadModeTest extends AbstractCxfWsdlFirstTest { + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } @BeforeClass public static void startService() { diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstProcessorTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstProcessorTest.java index 0dcfc8e25cab8..64580aa5d5072 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstProcessorTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstProcessorTest.java @@ -25,6 +25,10 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; public class CxfWsdlFirstProcessorTest extends AbstractCxfWsdlFirstTest { + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } protected ClassPathXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext(""org/apache/camel/component/cxf/WsdlFirstProcessor.xml""); diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstTest.java index 4fdf0390318c2..71237e359aaf5 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstTest.java @@ -41,6 +41,10 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; public class CxfWsdlFirstTest extends AbstractCxfWsdlFirstTest { + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } protected ClassPathXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext(""org/apache/camel/component/cxf/WsdlFirstBeans.xml""); diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/converter/CxfPayloadConverterTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/converter/CxfPayloadConverterTest.java index adc093a53375c..e5e915ca4c6e1 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/converter/CxfPayloadConverterTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/converter/CxfPayloadConverterTest.java @@ -41,6 +41,10 @@ public class CxfPayloadConverterTest extends ExchangeTestSupport { private CxfPayload payload; private CxfPayload emptyPayload; private FileInputStream inputStream; + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } @Override @Before diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerTest.java index 00bb7c29633f0..e4fd5798a1f54 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerTest.java @@ -49,6 +49,10 @@ public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(inMessage.getHeader(Exchange.HTTP_QUERY, String.class)); } } + @Override + public boolean isCreateCamelContextPerClass() { + return true; + } public int getPort1() { return port1; diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsRouterTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsRouterTest.java index 3506b2d6fa37e..7527d4784b45c 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsRouterTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsRouterTest.java @@ -21,6 +21,7 @@ import org.apache.camel.test.junit4.CamelSpringTestSupport; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; @@ -154,6 +155,9 @@ public void testPostConsumer() throws Exception { assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(""124Jack"", EntityUtils.toString(response.getEntity())); + + HttpDelete del = new HttpDelete(""http://localhost:"" + PORT0 + ""/CxfRsRouterTest/route/customerservice/customers/124/""); + httpclient.execute(del); } finally { httpclient.getConnectionManager().shutdown(); } @@ -174,6 +178,9 @@ public void testPostConsumerUniqueResponseCode() throws Exception { assertEquals(201, response.getStatusLine().getStatusCode()); assertEquals(""124Jack"", EntityUtils.toString(response.getEntity())); + + HttpDelete del = new HttpDelete(""http://localhost:"" + PORT0 + ""/CxfRsRouterTest/route/customerservice/customers/124/""); + httpclient.execute(del); } finally { httpclient.getConnectionManager().shutdown(); } diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomerService.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomerService.java index 1dbdb72f4422e..c90b4bb1ed600 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomerService.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomerService.java @@ -120,7 +120,9 @@ public Response deleteCustomer(@PathParam(""id"") String id) { } else { r = Response.notModified().build(); } - + if (idNumber == currentId) { + --currentId; + } return r; } diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/BrowsableQueueTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/BrowsableQueueTest.java index 896977f5456ff..966b5a1631e32 100644 --- a/components/camel-jms/src/test/java/org/apache/camel/component/jms/BrowsableQueueTest.java +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/BrowsableQueueTest.java @@ -24,11 +24,14 @@ import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.test.junit4.CamelTestSupport; + +import org.junit.After; +import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge; +import static org.apache.camel.component.jms.JmsComponent.jmsComponent; /** * @version @@ -41,16 +44,29 @@ public class BrowsableQueueTest extends CamelTestSupport { protected int counter; protected Object[] expectedBodies = {""body1"", ""body2""}; + @Before + public void setUp() throws Exception { + long start = System.currentTimeMillis(); + super.setUp(); + System.out.println(""Start: "" + (System.currentTimeMillis() - start)); + } + @After + public void tearDown() throws Exception { + long start = System.currentTimeMillis(); + super.tearDown(); + System.out.println(""Stop: "" + (System.currentTimeMillis() - start)); + } + @Test public void testSendMessagesThenBrowseQueue() throws Exception { // send some messages for (int i = 0; i < expectedBodies.length; i++) { Object expectedBody = expectedBodies[i]; - template.sendBodyAndHeader(""activemq:test.b"", expectedBody, ""counter"", i); + template.sendBodyAndHeader(""activemq:BrowsableQueueTest.b"", expectedBody, ""counter"", i); } // now lets browse the queue - JmsQueueEndpoint endpoint = getMandatoryEndpoint(""activemq:test.b?maximumBrowseSize=6"", JmsQueueEndpoint.class); + JmsQueueEndpoint endpoint = getMandatoryEndpoint(""activemq:BrowsableQueueTest.b?maximumBrowseSize=6"", JmsQueueEndpoint.class); assertEquals(6, endpoint.getMaximumBrowseSize()); List list = endpoint.getExchanges(); LOG.debug(""Received: "" + list); @@ -80,8 +96,8 @@ protected void sendExchange(final Object expectedBody) { protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); - ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory(); - camelContext.addComponent(componentName, jmsComponentAutoAcknowledge(connectionFactory)); + JmsComponent comp = jmsComponent(CamelJmsTestHelper.getSharedConfig()); + camelContext.addComponent(componentName, comp); return camelContext; } @@ -89,7 +105,7 @@ protected CamelContext createCamelContext() throws Exception { protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { - from(""activemq:test.a"").to(""activemq:test.b""); + from(""activemq:BrowsableQueueTest.a"").to(""activemq:BrowsableQueueTest.b""); } }; } diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/ConsumeMessageConverterTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/ConsumeMessageConverterTest.java index 2e06ccb8942a2..ac4fd990b7dd6 100644 --- a/components/camel-jms/src/test/java/org/apache/camel/component/jms/ConsumeMessageConverterTest.java +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/ConsumeMessageConverterTest.java @@ -32,7 +32,7 @@ import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.MessageConverter; -import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge; +import static org.apache.camel.component.jms.JmsComponent.jmsComponent; /** * @version @@ -49,8 +49,7 @@ protected JndiRegistry createRegistry() throws Exception { protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); - ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory(); - camelContext.addComponent(""activemq"", jmsComponentAutoAcknowledge(connectionFactory)); + camelContext.addComponent(""activemq"", jmsComponent(CamelJmsTestHelper.getSharedConfig())); return camelContext; } @@ -61,7 +60,7 @@ public void testTextMessage() throws Exception { mock.expectedMessageCount(1); mock.message(0).body().isInstanceOf(TextMessage.class); - template.sendBody(""activemq:queue:hello"", ""Hello World""); + template.sendBody(""activemq:queue:ConsumeMessageConverterTest.hello"", ""Hello World""); assertMockEndpointsSatisfied(); } @@ -72,7 +71,7 @@ public void testBytesMessage() throws Exception { mock.expectedMessageCount(1); mock.message(0).body().isInstanceOf(BytesMessage.class); - template.sendBody(""activemq:queue:hello"", ""Hello World"".getBytes()); + template.sendBody(""activemq:queue:ConsumeMessageConverterTest.hello"", ""Hello World"".getBytes()); assertMockEndpointsSatisfied(); } @@ -80,7 +79,7 @@ public void testBytesMessage() throws Exception { protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { - from(""activemq:queue:hello?messageConverter=#myMessageConverter"").to(""mock:result""); + from(""activemq:queue:ConsumeMessageConverterTest.hello?messageConverter=#myMessageConverter"").to(""mock:result""); } }; } diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/FileRouteToJmsToFileTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/FileRouteToJmsToFileTest.java index c1b570225fa34..ca060781651f8 100644 --- a/components/camel-jms/src/test/java/org/apache/camel/component/jms/FileRouteToJmsToFileTest.java +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/FileRouteToJmsToFileTest.java @@ -27,7 +27,7 @@ import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; -import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge; +import static org.apache.camel.component.jms.JmsComponent.jmsComponent; /** * Unit test that we can do file over JMS to file. @@ -39,7 +39,7 @@ public class FileRouteToJmsToFileTest extends CamelTestSupport { @Test public void testRouteFileToFile() throws Exception { deleteDirectory(""target/file2file""); - NotifyBuilder notify = new NotifyBuilder(context).from(""activemq:queue:hello"").whenDone(1).create(); + NotifyBuilder notify = new NotifyBuilder(context).from(""activemq:queue:FileRouteToJmsToFileTest.hello"").whenDone(1).create(); MockEndpoint mock = getMockEndpoint(""mock:result""); mock.expectedMessageCount(1); @@ -58,8 +58,7 @@ public void testRouteFileToFile() throws Exception { protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); - ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory(); - camelContext.addComponent(componentName, jmsComponentAutoAcknowledge(connectionFactory)); + camelContext.addComponent(componentName, jmsComponent(CamelJmsTestHelper.getSharedConfig())); return camelContext; } @@ -67,9 +66,9 @@ protected CamelContext createCamelContext() throws Exception { protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { - from(""file://target/file2file/in"").to(""activemq:queue:hello""); + from(""file://target/file2file/in"").to(""activemq:queue:FileRouteToJmsToFileTest.hello""); - from(""activemq:queue:hello"").to(""file://target/file2file/out"", ""mock:result""); + from(""activemq:queue:FileRouteToJmsToFileTest.hello"").to(""file://target/file2file/out"", ""mock:result""); } }; } diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsAutoStartupTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsAutoStartupTest.java index a62787c32009c..e643a301812d6 100644 --- a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsAutoStartupTest.java +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsAutoStartupTest.java @@ -44,7 +44,7 @@ public void testAutoStartup() throws Exception { // should be stopped by default mock.expectedMessageCount(0); - template.sendBody(""activemq:queue:foo"", ""Hello World""); + template.sendBody(""activemq:queue:JmsAutoStartupTest.foo"", ""Hello World""); Thread.sleep(2000); @@ -64,7 +64,7 @@ protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { - endpoint = context.getEndpoint(""activemq:queue:foo?autoStartup=false"", JmsEndpoint.class); + endpoint = context.getEndpoint(""activemq:queue:JmsAutoStartupTest.foo?autoStartup=false"", JmsEndpoint.class); from(endpoint).to(""mock:result""); } diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsBatchResequencerJMSPriorityTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsBatchResequencerJMSPriorityTest.java index a86c1e38dceb0..2460e0265bc51 100644 --- a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsBatchResequencerJMSPriorityTest.java +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsBatchResequencerJMSPriorityTest.java @@ -40,14 +40,14 @@ public void testBatchResequencerJMSPriority() throws Exception { mock.expectedBodiesReceived(""G"", ""A"", ""B"", ""E"", ""H"", ""C"", ""D"", ""F""); // must use preserveMessageQos=true to be able to specify the JMSPriority to be used - template.sendBodyAndHeader(""jms:queue:foo?preserveMessageQos=true"", ""A"", ""JMSPriority"", 6); - template.sendBodyAndHeader(""jms:queue:foo?preserveMessageQos=true"", ""B"", ""JMSPriority"", 6); - template.sendBodyAndHeader(""jms:queue:foo?preserveMessageQos=true"", ""C"", ""JMSPriority"", 4); - template.sendBodyAndHeader(""jms:queue:foo?preserveMessageQos=true"", ""D"", ""JMSPriority"", 4); - template.sendBodyAndHeader(""jms:queue:foo?preserveMessageQos=true"", ""E"", ""JMSPriority"", 6); - template.sendBodyAndHeader(""jms:queue:foo?preserveMessageQos=true"", ""F"", ""JMSPriority"", 4); - template.sendBodyAndHeader(""jms:queue:foo?preserveMessageQos=true"", ""G"", ""JMSPriority"", 8); - template.sendBodyAndHeader(""jms:queue:foo?preserveMessageQos=true"", ""H"", ""JMSPriority"", 6); + template.sendBodyAndHeader(""jms:queue:JmsBatchResequencerJMSPriorityTest.foo?preserveMessageQos=true"", ""A"", ""JMSPriority"", 6); + template.sendBodyAndHeader(""jms:queue:JmsBatchResequencerJMSPriorityTest.foo?preserveMessageQos=true"", ""B"", ""JMSPriority"", 6); + template.sendBodyAndHeader(""jms:queue:JmsBatchResequencerJMSPriorityTest.foo?preserveMessageQos=true"", ""C"", ""JMSPriority"", 4); + template.sendBodyAndHeader(""jms:queue:JmsBatchResequencerJMSPriorityTest.foo?preserveMessageQos=true"", ""D"", ""JMSPriority"", 4); + template.sendBodyAndHeader(""jms:queue:JmsBatchResequencerJMSPriorityTest.foo?preserveMessageQos=true"", ""E"", ""JMSPriority"", 6); + template.sendBodyAndHeader(""jms:queue:JmsBatchResequencerJMSPriorityTest.foo?preserveMessageQos=true"", ""F"", ""JMSPriority"", 4); + template.sendBodyAndHeader(""jms:queue:JmsBatchResequencerJMSPriorityTest.foo?preserveMessageQos=true"", ""G"", ""JMSPriority"", 8); + template.sendBodyAndHeader(""jms:queue:JmsBatchResequencerJMSPriorityTest.foo?preserveMessageQos=true"", ""H"", ""JMSPriority"", 6); assertMockEndpointsSatisfied(); } @@ -55,7 +55,7 @@ public void testBatchResequencerJMSPriority() throws Exception { protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); - ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory(); + ConnectionFactory connectionFactory = CamelJmsTestHelper.getSharedConnectionFactory(); camelContext.addComponent(""jms"", jmsComponentAutoAcknowledge(connectionFactory)); return camelContext; @@ -67,7 +67,7 @@ protected RouteBuilder createRouteBuilder() throws Exception { @Override public void configure() throws Exception { // START SNIPPET: e1 - from(""jms:queue:foo"") + from(""jms:queue:JmsBatchResequencerJMSPriorityTest.foo"") // sort by JMSPriority by allowing duplicates (message can have same JMSPriority) // and use reverse ordering so 9 is first output (most important), and 0 is last // use batch mode and fire every 3th second diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsComponentTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsComponentTest.java index 40d74a424df78..fb97686fda8d0 100644 --- a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsComponentTest.java +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsComponentTest.java @@ -34,7 +34,7 @@ public class JmsComponentTest extends CamelTestSupport { @Test public void testComponentOptions() throws Exception { - String reply = template.requestBody(""activemq123:queue:hello?requestTimeout=5000"", ""Hello World"", String.class); + String reply = template.requestBody(""activemq123:queue:JmsComponentTest.hello?requestTimeout=5000"", ""Hello World"", String.class); assertEquals(""Bye World"", reply); assertEquals(true, endpoint.isAcceptMessagesWhileStopping()); @@ -60,7 +60,7 @@ public void testComponentOptions() throws Exception { protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); - ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory(); + ConnectionFactory connectionFactory = CamelJmsTestHelper.getSharedConnectionFactory(); JmsComponent comp = jmsComponentAutoAcknowledge(connectionFactory); comp.setAcceptMessagesWhileStopping(true); @@ -84,7 +84,7 @@ protected CamelContext createCamelContext() throws Exception { camelContext.addComponent(componentName, comp); - endpoint = (JmsEndpoint) comp.createEndpoint(""queue:hello""); + endpoint = (JmsEndpoint) comp.createEndpoint(""queue:JmsComponentTest.hello""); return camelContext; } diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsConsumerRestartPickupConfigurationChangesTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsConsumerRestartPickupConfigurationChangesTest.java index 8b5e8e1eb070e..f421e09088aa6 100644 --- a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsConsumerRestartPickupConfigurationChangesTest.java +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsConsumerRestartPickupConfigurationChangesTest.java @@ -33,7 +33,7 @@ public class JmsConsumerRestartPickupConfigurationChangesTest extends CamelTestS @Test public void testRestartJmsConsumerPickupChanges() throws Exception { - JmsEndpoint endpoint = context.getEndpoint(""activemq:queue:foo"", JmsEndpoint.class); + JmsEndpoint endpoint = context.getEndpoint(""activemq:queue:JmsConsumerRestartPickupConfigurationChangesTest.foo"", JmsEndpoint.class); JmsConsumer consumer = endpoint.createConsumer(new Processor() { public void process(Exchange exchange) throws Exception { template.send(""mock:result"", exchange); @@ -44,7 +44,7 @@ public void process(Exchange exchange) throws Exception { MockEndpoint result = getMockEndpoint(""mock:result""); result.expectedBodiesReceived(""Hello World""); - template.sendBody(""activemq:queue:foo"", ""Hello World""); + template.sendBody(""activemq:queue:JmsConsumerRestartPickupConfigurationChangesTest.foo"", ""Hello World""); assertMockEndpointsSatisfied(); consumer.stop(); @@ -58,7 +58,7 @@ public void process(Exchange exchange) throws Exception { result.reset(); result.expectedBodiesReceived(""Bye World""); - template.sendBody(""activemq:queue:bar"", ""Bye World""); + template.sendBody(""activemq:queue:JmsConsumerRestartPickupConfigurationChangesTest.bar"", ""Bye World""); assertMockEndpointsSatisfied(); consumer.stop(); @@ -67,7 +67,7 @@ public void process(Exchange exchange) throws Exception { protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); - ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory(); + ConnectionFactory connectionFactory = CamelJmsTestHelper.getSharedConnectionFactory(); camelContext.addComponent(""activemq"", jmsComponentAutoAcknowledge(connectionFactory)); return camelContext; diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsProduerConcurrentTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsProduerConcurrentTest.java index ba919e5addbf6..fd9dab74a9bb2 100644 --- a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsProduerConcurrentTest.java +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsProduerConcurrentTest.java @@ -64,7 +64,7 @@ public Object call() throws Exception { protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); - ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory(); + ConnectionFactory connectionFactory = CamelJmsTestHelper.getSharedConnectionFactory(); camelContext.addComponent(""jms"", jmsComponentAutoAcknowledge(connectionFactory)); return camelContext; @@ -75,9 +75,9 @@ protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { - from(""direct:start"").to(""jms:queue:foo""); + from(""direct:start"").to(""jms:queue:foo-JmsProducerConcurrentTest""); - from(""jms:queue:foo"").to(""mock:result""); + from(""jms:queue:foo-JmsProducerConcurrentTest"").to(""mock:result""); } }; } diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsProduerConcurrentWithReplyTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsProduerConcurrentWithReplyTest.java index d7bf2dc9b6f50..15fcead7bf1e8 100644 --- a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsProduerConcurrentWithReplyTest.java +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsProduerConcurrentWithReplyTest.java @@ -73,7 +73,7 @@ public Object call() throws Exception { protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); - ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory(); + ConnectionFactory connectionFactory = CamelJmsTestHelper.getSharedConnectionFactory(); camelContext.addComponent(""jms"", jmsComponentAutoAcknowledge(connectionFactory)); return camelContext; @@ -84,9 +84,9 @@ protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { - from(""direct:start"").to(""jms:queue:foo""); + from(""direct:start"").to(""jms:queue:foo-JmsProduerConcurrentWithReplyTest""); - from(""jms:queue:foo?concurrentConsumers=5"").transform(simple(""Bye ${in.body}"")).to(""mock:result""); + from(""jms:queue:foo-JmsProduerConcurrentWithReplyTest?concurrentConsumers=5"").transform(simple(""Bye ${in.body}"")).to(""mock:result""); } }; }" 8c475876dda2507977fd7282c37462136400daf2,drools,-Added fixes for waltz to run waltz50--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@7071 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-,c,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Edge.java b/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Edge.java index d114ffd5441..b1ec6212171 100644 --- a/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Edge.java +++ b/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Edge.java @@ -39,6 +39,10 @@ public class Edge { final public static String MINUS = ""-""; + public Edge() { + + } + public Edge(final int p1, final int p2, final boolean joined, diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Junction.java b/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Junction.java index dc50219454d..ca1e1b51585 100644 --- a/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Junction.java +++ b/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Junction.java @@ -39,7 +39,11 @@ public class Junction { private int basePoint; private String type; - + + public Junction() { + + } + public Junction(final int p1, final int p2, final int p3, diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Line.java b/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Line.java index 0c424db3448..158900158fd 100644 --- a/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Line.java +++ b/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Line.java @@ -26,6 +26,10 @@ public class Line { private int p2; + public Line() { + + } + public Line(final int p1, final int p2) { this.p1 = p1; diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Stage.java b/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Stage.java index 252ba075d3a..f5c0ba87174 100644 --- a/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Stage.java +++ b/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Stage.java @@ -51,6 +51,10 @@ public class Stage private int value; + public Stage() { + + } + public Stage(final int value) { this.value = value; } diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Waltz.java b/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Waltz.java index 4cfe78e93dd..2bca544472d 100644 --- a/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Waltz.java +++ b/drools-compiler/src/test/java/org/drools/integrationtests/waltz/Waltz.java @@ -56,10 +56,15 @@ public void testWaltz() { // workingMemory.addEventListener( agendaListener ); //go ! - //this.loadLines( workingMemory, ""waltz12.dat"" ); - - final Stage stage = new Stage( Stage.START ); - workingMemory.assertObject( stage ); + this.loadLines( workingMemory, + ""waltz50.dat"" ); + + //final Stage stage = new Stage( Stage.START ); + //workingMemory.assertObject( stage ); + + Stage stage = new Stage(Stage.DUPLICATE); + workingMemory.assertObject( stage ); + workingMemory.fireAllRules(); } catch ( final Throwable t ) { t.printStackTrace(); @@ -100,7 +105,7 @@ private void loadLines(final WorkingMemory wm, final Matcher m = pat.matcher( line ); if ( m.matches() ) { final Line l = new Line( Integer.parseInt( m.group( 1 ) ), - Integer.parseInt( m.group( 2 ) ) ); + Integer.parseInt( m.group( 2 ) ) ); wm.assertObject( l ); } line = reader.readLine();" 19152416a44473325a6c3605f9accc4fee379b63,elasticsearch,add an index level setting to disable/enable- purging of expired docs --,a,https://github.com/elastic/elasticsearch,"diff --git a/src/main/java/org/elasticsearch/indices/ttl/IndicesTTLService.java b/src/main/java/org/elasticsearch/indices/ttl/IndicesTTLService.java index ae4a010e95c40..f000ba6987225 100644 --- a/src/main/java/org/elasticsearch/indices/ttl/IndicesTTLService.java +++ b/src/main/java/org/elasticsearch/indices/ttl/IndicesTTLService.java @@ -31,6 +31,8 @@ import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.client.Client; +import org.elasticsearch.cluster.ClusterService; +import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.common.component.AbstractLifecycleComponent; import org.elasticsearch.common.inject.Inject; @@ -65,8 +67,13 @@ public class IndicesTTLService extends AbstractLifecycleComponent getShardsToPurge() { List shardsToPurge = new ArrayList(); for (IndexService indexService : indicesService) { + // check the value of disable_purge for this index + IndexMetaData indexMetaData = clusterService.state().metaData().index(indexService.index().name()); + boolean disablePurge = indexMetaData.settings().getAsBoolean(""index.ttl.disable_purge"", false); + if (disablePurge) { + continue; + } + // should be optimized with the hasTTL flag FieldMappers ttlFieldMappers = indexService.mapperService().name(TTLFieldMapper.NAME); if (ttlFieldMappers == null) {" ca849f196990eec942468efaef3719f829c265eb,orientdb,Improved management of distributed cluster nodes--,p,https://github.com/orientechnologies/orientdb,"diff --git a/client/src/main/java/com/orientechnologies/orient/client/remote/OServerAdmin.java b/client/src/main/java/com/orientechnologies/orient/client/remote/OServerAdmin.java index 6ad17e70a96..80b8a0fa780 100644 --- a/client/src/main/java/com/orientechnologies/orient/client/remote/OServerAdmin.java +++ b/client/src/main/java/com/orientechnologies/orient/client/remote/OServerAdmin.java @@ -117,7 +117,7 @@ public OServerAdmin deleteDatabase() throws IOException { } public OServerAdmin shareDatabase(final String iDatabaseName, final String iDatabaseUserName, final String iDatabaseUserPassword, - final String iRemoteName) throws IOException { + final String iRemoteName, final String iMode) throws IOException { try { storage.writeCommand(OChannelDistributedProtocol.REQUEST_DISTRIBUTED_DB_SHARE_SENDER); @@ -125,11 +125,13 @@ public OServerAdmin shareDatabase(final String iDatabaseName, final String iData storage.getNetwork().writeString(iDatabaseUserName); storage.getNetwork().writeString(iDatabaseUserPassword); storage.getNetwork().writeString(iRemoteName); + storage.getNetwork().writeString(iMode); storage.getNetwork().flush(); storage.getNetwork().readStatus(); - OLogManager.instance().debug(this, ""Database %s has been shared with the server %s."", iDatabaseName, iRemoteName); + OLogManager.instance().debug(this, ""Database '%s' has been shared in mode '%s' with the server '%s'"", iDatabaseName, iMode, + iRemoteName); } catch (Exception e) { OLogManager.instance().exception(""Can't share the database: "" + iDatabaseName, e, OStorageException.class); diff --git a/server/src/main/java/com/orientechnologies/orient/server/handler/OServerHandler.java b/server/src/main/java/com/orientechnologies/orient/server/handler/OServerHandler.java index 6a1603e0075..e3e174cf388 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/handler/OServerHandler.java +++ b/server/src/main/java/com/orientechnologies/orient/server/handler/OServerHandler.java @@ -40,17 +40,20 @@ public interface OServerHandler extends OService { /** * Callback invoked before a client request is processed. */ - public void onBeforeClientRequest(OClientConnection iConnection, byte iRequestType); + public void onBeforeClientRequest(OClientConnection iConnection, Object iRequestType); /** * Callback invoked after a client request is processed. */ - public void onAfterClientRequest(OClientConnection iConnection, byte iRequestType); + public void onAfterClientRequest(OClientConnection iConnection, Object iRequestType); /** * Callback invoked when a client connection has errors. + * + * @param iThrowable + * Throwable instance received */ - public void onClientError(OClientConnection iConnection); + public void onClientError(OClientConnection iConnection, Throwable iThrowable); /** * Configures the handler. Called at startup. diff --git a/server/src/main/java/com/orientechnologies/orient/server/handler/OServerHandlerAbstract.java b/server/src/main/java/com/orientechnologies/orient/server/handler/OServerHandlerAbstract.java index 39a5c4d457d..a146ac509fa 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/handler/OServerHandlerAbstract.java +++ b/server/src/main/java/com/orientechnologies/orient/server/handler/OServerHandlerAbstract.java @@ -25,12 +25,12 @@ public void onClientConnection(final OClientConnection iConnection) { public void onClientDisconnection(final OClientConnection iConnection) { } - public void onBeforeClientRequest(final OClientConnection iConnection, final byte iRequestType) { + public void onBeforeClientRequest(final OClientConnection iConnection, final Object iRequestType) { } - public void onAfterClientRequest(final OClientConnection iConnection, final byte iRequestType) { + public void onAfterClientRequest(final OClientConnection iConnection, final Object iRequestType) { } - public void onClientError(final OClientConnection iConnection) { + public void onClientError(final OClientConnection iConnection, final Throwable iThrowable) { } } diff --git a/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerManager.java b/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerManager.java index 483c76c6359..8794e058c3f 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerManager.java +++ b/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerManager.java @@ -19,6 +19,7 @@ import java.net.InetAddress; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import javax.crypto.SecretKey; @@ -26,12 +27,15 @@ import com.orientechnologies.common.concur.resource.OSharedResourceExternal; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.Orient; +import com.orientechnologies.orient.core.db.ODatabase; +import com.orientechnologies.orient.core.db.ODatabaseComplex; +import com.orientechnologies.orient.core.db.ODatabaseLifecycleListener; import com.orientechnologies.orient.core.exception.OConfigurationException; import com.orientechnologies.orient.core.record.ORecordInternal; +import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.security.OSecurityManager; import com.orientechnologies.orient.core.serialization.OBase64Utils; import com.orientechnologies.orient.core.tx.OTransactionEntry; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryProtocol; import com.orientechnologies.orient.server.OClientConnection; import com.orientechnologies.orient.server.OServer; import com.orientechnologies.orient.server.config.OServerHandlerConfiguration; @@ -57,19 +61,20 @@ * @see ODistributedServerDiscoveryListener, ODistributedServerDiscoverySignaler * */ -public class ODistributedServerManager extends OServerHandlerAbstract { +public class ODistributedServerManager extends OServerHandlerAbstract { protected OServer server; protected String name; + protected String id; protected SecretKey securityKey; protected String securityAlgorithm; protected InetAddress networkMulticastAddress; protected int networkMulticastPort; - protected int networkMulticastHeartbeat; // IN MS - protected int networkTimeoutLeader; // IN MS - protected int networkTimeoutNode; // IN MS - private int networkHeartbeatDelay; // IN MS - protected int serverUpdateDelay; // IN MS + protected int networkMulticastHeartbeat; // IN + protected int networkTimeoutLeader; // IN + protected int networkTimeoutNode; // IN + private int networkHeartbeatDelay; // IN + protected int serverUpdateDelay; // IN protected int serverOutSynchMaxBuffers; private ODistributedServerDiscoverySignaler discoverySignaler; @@ -78,7 +83,7 @@ public class ODistributedServerManager extends OServerHandlerAbstract { private ODistributedServerRecordHook trigger; private final OSharedResourceExternal lock = new OSharedResourceExternal(); - private final HashMap nodes = new HashMap(); ; + private final HashMap nodes = new LinkedHashMap(); ; static final String CHECKSUM = ""ChEcKsUm1976""; @@ -88,8 +93,11 @@ public class ODistributedServerManager extends OServerHandlerAbstract { private OServerNetworkListener distributedNetworkListener; private ONetworkProtocolDistributed leaderConnection; public long lastHeartBeat; + private ODocument clusterConfiguration; public void startup() { + trigger = new ODistributedServerRecordHook(this); + // LAUNCH THE SIGNAL AND WAIT FOR A CONNECTION discoverySignaler = new ODistributedServerDiscoverySignaler(this, distributedNetworkListener); } @@ -195,6 +203,9 @@ else if (leaderConnection != null) // STOP THE CHECK OF HEART-BEAT leaderCheckerTask.cancel(); + if (clusterConfiguration == null) + clusterConfiguration = createDatabaseConfiguration(); + // NO NODE HAS JOINED: BECAME THE LEADER AND LISTEN FOR OTHER NODES discoveryListener = new ODistributedServerDiscoveryListener(this, distributedNetworkListener); @@ -203,21 +214,8 @@ else if (leaderConnection != null) } } - /** - * Install the trigger to catch all the events on records - */ - @Override - public void onAfterClientRequest(final OClientConnection iConnection, final byte iRequestType) { - if (iRequestType == OChannelBinaryProtocol.REQUEST_DB_OPEN || iRequestType == OChannelBinaryProtocol.REQUEST_DB_CREATE) { - trigger = new ODistributedServerRecordHook(this, iConnection); - iConnection.database.registerHook(trigger); - - // TODO: SEND THE CLUSTER CONFIG TO THE CLIENT - } - } - @Override - public void onClientError(final OClientConnection iConnection) { + public void onClientError(final OClientConnection iConnection, final Throwable iThrowable) { // handleNodeFailure(node); } @@ -295,6 +293,8 @@ else if (""server.outsynch.maxbuffers"".equalsIgnoreCase(param.name)) ""Can't find a configured network listener with 'distributed' protocol. Can't start distributed node"", null, OConfigurationException.class); + id = distributedNetworkListener.getInboundAddr().getHostName() + "":"" + distributedNetworkListener.getInboundAddr().getPort(); + } catch (Exception e) { throw new OConfigurationException(""Can't configure OrientDB Server as Cluster Node"", e); } @@ -357,10 +357,8 @@ public String getName() { /** * Distributed the request to all the configured nodes. Each node has the responsibility to bring the message early (synch-mode) * or using an asynchronous queue. - * - * @param iConnection */ - public void distributeRequest(final OClientConnection iConnection, final OTransactionEntry> iTransactionEntry) { + public void distributeRequest(final OTransactionEntry> iTransactionEntry) { lock.acquireSharedLock(); try { @@ -382,10 +380,6 @@ public int getNetworkHeartbeatDelay() { return networkHeartbeatDelay; } - private static String getNodeName(final String iServerAddress, final int iServerPort) { - return iServerAddress + "":"" + iServerPort; - } - public long getLastHeartBeat() { return lastHeartBeat; } @@ -393,4 +387,25 @@ public long getLastHeartBeat() { public void updateHeartBeatTime() { this.lastHeartBeat = System.currentTimeMillis(); } + + public ODocument getClusterConfiguration() { + return clusterConfiguration; + } + + public String getId() { + return id; + } + + private static String getNodeName(final String iServerAddress, final int iServerPort) { + return iServerAddress + "":"" + iServerPort; + } + + private ODocument createDatabaseConfiguration() { + clusterConfiguration = new ODocument(); + + clusterConfiguration.field(""servers"", new ODocument(getId(), new ODocument(""update-delay"", getServerUpdateDelay()))); + clusterConfiguration.field(""clusters"", new ODocument(""*"", new ODocument(""owner"", getId()))); + + return clusterConfiguration; + } } diff --git a/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerNode.java b/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerNode.java index 3d82d444c6b..9d608990124 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerNode.java +++ b/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerNode.java @@ -22,12 +22,15 @@ import java.util.Map; import com.orientechnologies.common.log.OLogManager; +import com.orientechnologies.orient.core.command.OCommandOutputListener; import com.orientechnologies.orient.core.config.OContextConfiguration; import com.orientechnologies.orient.core.config.OGlobalConfiguration; +import com.orientechnologies.orient.core.db.record.ODatabaseRecord; +import com.orientechnologies.orient.core.db.tool.ODatabaseExport; import com.orientechnologies.orient.core.record.ORecordInternal; -import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.tx.OTransactionEntry; import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryClient; +import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryOutputStream; import com.orientechnologies.orient.enterprise.channel.distributed.OChannelDistributedProtocol; /** @@ -36,18 +39,19 @@ * @author Luca Garulli (l.garulli--at--orientechnologies.com) * */ -public class ODistributedServerNode { +public class ODistributedServerNode implements OCommandOutputListener { public enum STATUS { DISCONNECTED, CONNECTING, CONNECTED, SYNCHRONIZING } + private String id; public String networkAddress; public int networkPort; public Date joinedOn; private ODistributedServerManager manager; public OChannelBinaryClient channel; private OContextConfiguration configuration; - private STATUS status = STATUS.DISCONNECTED; + private volatile STATUS status = STATUS.DISCONNECTED; private Map storages = new HashMap(); private List>> bufferedChanges = new ArrayList>>(); @@ -57,6 +61,7 @@ public ODistributedServerNode(final ODistributedServerManager iNode, final Strin networkPort = iServerPort; joinedOn = new Date(); configuration = new OContextConfiguration(); + id = networkAddress + "":"" + networkPort; status = STATUS.CONNECTING; } @@ -83,9 +88,13 @@ public void sendRequest(final OTransactionEntry> iRequest) th // BUFFER EXCEEDS THE CONFIGURED LIMIT: REMOVE MYSELF AS NODE manager.removeNode(this); bufferedChanges.clear(); - } else + } else { // BUFFERIZE THE REQUEST bufferedChanges.add(iRequest); + + OLogManager.instance().info(this, ""Server node '%s' is temporary disconnected, buffering change %d/%d for the record %s"", + id, bufferedChanges.size(), manager.serverOutSynchMaxBuffers, iRequest.getRecord().getIdentity()); + } } } else { final ORecordInternal record = iRequest.getRecord(); @@ -93,42 +102,58 @@ public void sendRequest(final OTransactionEntry> iRequest) th try { switch (iRequest.status) { case OTransactionEntry.CREATED: - channel.writeByte(OChannelDistributedProtocol.REQUEST_RECORD_CREATE); - channel.writeInt(0); - channel.writeShort((short) record.getIdentity().getClusterId()); - channel.writeBytes(record.toStream()); - channel.writeByte(record.getRecordType()); - channel.flush(); - - channel.readStatus(); + channel.acquireExclusiveLock(); + try { + channel.writeByte(OChannelDistributedProtocol.REQUEST_RECORD_CREATE); + channel.writeInt(0); + channel.writeShort((short) record.getIdentity().getClusterId()); + channel.writeBytes(record.toStream()); + channel.writeByte(record.getRecordType()); + channel.flush(); + + channel.readStatus(); + + } finally { + channel.releaseExclusiveLock(); + } break; case OTransactionEntry.UPDATED: - channel.writeByte(OChannelDistributedProtocol.REQUEST_RECORD_UPDATE); - channel.writeInt(0); - channel.writeShort((short) record.getIdentity().getClusterId()); - channel.writeLong(record.getIdentity().getClusterPosition()); - channel.writeBytes(record.toStream()); - channel.writeInt(record.getVersion()); - channel.writeByte(record.getRecordType()); - channel.flush(); - - readStatus(); - - channel.readInt(); + channel.acquireExclusiveLock(); + try { + channel.writeByte(OChannelDistributedProtocol.REQUEST_RECORD_UPDATE); + channel.writeInt(0); + channel.writeShort((short) record.getIdentity().getClusterId()); + channel.writeLong(record.getIdentity().getClusterPosition()); + channel.writeBytes(record.toStream()); + channel.writeInt(record.getVersion()); + channel.writeByte(record.getRecordType()); + channel.flush(); + + readStatus(); + + channel.readInt(); + } finally { + channel.releaseExclusiveLock(); + } break; case OTransactionEntry.DELETED: - channel.writeByte(OChannelDistributedProtocol.REQUEST_RECORD_DELETE); - channel.writeInt(0); - channel.writeShort((short) record.getIdentity().getClusterId()); - channel.writeLong(record.getIdentity().getClusterPosition()); - channel.writeInt(record.getVersion()); - channel.flush(); - - readStatus(); - - channel.readLong(); + channel.acquireExclusiveLock(); + try { + channel.writeByte(OChannelDistributedProtocol.REQUEST_RECORD_DELETE); + channel.writeInt(0); + channel.writeShort((short) record.getIdentity().getClusterId()); + channel.writeLong(record.getIdentity().getClusterPosition()); + channel.writeInt(record.getVersion()); + channel.flush(); + + readStatus(); + + channel.readLong(); + } finally { + channel.releaseExclusiveLock(); + } break; } } catch (RuntimeException e) { @@ -175,15 +200,13 @@ public void setAsTemporaryDisconnected(final int iServerOutSynchMaxBuffers) { } public void startSynchronization() { - final ODocument config = createDatabaseConfiguration(); - // SEND THE LAST CONFIGURATION TO THE NODE channel.acquireExclusiveLock(); try { channel.out.writeByte(OChannelDistributedProtocol.REQUEST_DISTRIBUTED_DB_CONFIG); channel.out.writeInt(0); - channel.writeBytes(config.toStream()); + channel.writeBytes(manager.getClusterConfiguration().toStream()); channel.flush(); readStatus(); @@ -202,9 +225,51 @@ public void startSynchronization() { @Override public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append(networkAddress).append("":"").append(networkPort); - return builder.toString(); + return id; + } + + public STATUS getStatus() { + return status; + } + + public void shareDatabase(final ODatabaseRecord iDatabase, final String iRemoteServerName, final String iEngineName, + final String iMode) throws IOException { + if (status == STATUS.DISCONNECTED) + throw new ODistributedSynchronizationException(""Can't share database '"" + iDatabase.getName() + ""' on remote server node '"" + + iRemoteServerName + ""' because is disconnected""); + + channel.acquireExclusiveLock(); + + try { + status = STATUS.SYNCHRONIZING; + + OLogManager.instance().info(this, + ""Sharing database '"" + iDatabase.getName() + ""' to remote server "" + iRemoteServerName + ""...""); + + // EXECUTE THE REQUEST ON REMOTE SERVER NODE + channel.writeByte(OChannelDistributedProtocol.REQUEST_DISTRIBUTED_DB_SHARE_RECEIVER); + channel.writeInt(0); + channel.writeString(iDatabase.getName()); + channel.writeString(iEngineName); + + OLogManager.instance().info(this, ""Exporting database '%s' via streaming to remote server node: %s..."", iDatabase.getName(), + iRemoteServerName); + + // START THE EXPORT GIVING AS OUTPUTSTREAM THE CHANNEL TO STREAM THE EXPORT + new ODatabaseExport(iDatabase, new OChannelBinaryOutputStream(channel), this).exportDatabase(); + + OLogManager.instance().info(this, ""Database exported correctly""); + + channel.readStatus(); + + status = STATUS.CONNECTED; + + } finally { + channel.releaseExclusiveLock(); + } + } + + public void onMessage(String iText) { } private void synchronizeDelta() throws IOException { @@ -212,8 +277,8 @@ private void synchronizeDelta() throws IOException { if (bufferedChanges.isEmpty()) return; - OLogManager.instance().info(this, ""Started realignment of remote node %s:%d after a reconnection. Found %d updates"", - networkAddress, networkPort, bufferedChanges.size()); + OLogManager.instance().info(this, ""Started realignment of remote node '%s' after a reconnection. Found %d updates"", id, + bufferedChanges.size()); status = STATUS.SYNCHRONIZING; @@ -222,6 +287,8 @@ private void synchronizeDelta() throws IOException { } bufferedChanges.clear(); + OLogManager.instance().info(this, ""Realignment of remote node '%s' done"", id); + status = STATUS.CONNECTED; } @@ -231,17 +298,4 @@ private void synchronizeDelta() throws IOException { private int readStatus() throws IOException { return channel.readStatus(); } - - private ODocument createDatabaseConfiguration() { - final ODocument config = new ODocument(); - - config.field(""servers"", new ODocument(manager.getName(), new ODocument(""update-delay"", manager.getServerUpdateDelay()))); - config.field(""clusters"", new ODocument(""*"", new ODocument(""owner"", manager.getName()))); - - return config; - } - - public STATUS getStatus() { - return status; - } } diff --git a/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerNodeChecker.java b/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerNodeChecker.java index efdbf3cf902..c669a9f1338 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerNodeChecker.java +++ b/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerNodeChecker.java @@ -45,7 +45,7 @@ public void run() { // CHECK EVERY SINGLE NODE for (ODistributedServerNode node : nodeList) { - if (node.getStatus() != STATUS.DISCONNECTED) + if (node.getStatus() == STATUS.CONNECTED) if (!node.sendHeartBeat(manager.networkTimeoutLeader)) { manager.handleNodeFailure(node); } diff --git a/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerRecordHook.java b/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerRecordHook.java index 37bc038dd3c..8ee04caf27a 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerRecordHook.java +++ b/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerRecordHook.java @@ -15,52 +15,75 @@ */ package com.orientechnologies.orient.server.handler.distributed; +import com.orientechnologies.common.log.OLogManager; +import com.orientechnologies.orient.core.Orient; +import com.orientechnologies.orient.core.db.ODatabase; +import com.orientechnologies.orient.core.db.ODatabaseComplex; +import com.orientechnologies.orient.core.db.ODatabaseLifecycleListener; import com.orientechnologies.orient.core.hook.ORecordHook; import com.orientechnologies.orient.core.record.ORecord; import com.orientechnologies.orient.core.record.ORecordInternal; import com.orientechnologies.orient.core.tx.OTransactionEntry; -import com.orientechnologies.orient.server.OClientConnection; /** * Record hook implementation. Catches all the relevant events and propagates to the cluster's slave nodes. * * @author Luca Garulli (l.garulli--at--orientechnologies.com) */ -public class ODistributedServerRecordHook implements ORecordHook { +public class ODistributedServerRecordHook implements ORecordHook, ODatabaseLifecycleListener { private ODistributedServerManager manager; - private OClientConnection connection; - public ODistributedServerRecordHook(final ODistributedServerManager iDistributedServerManager, final OClientConnection iConnection) { + /** + * Auto install itself as lifecycle listener for databases. + */ + public ODistributedServerRecordHook(final ODistributedServerManager iDistributedServerManager) { manager = iDistributedServerManager; - connection = iConnection; + Orient.instance().addDbLifecycleListener(this); } public void onTrigger(final TYPE iType, final ORecord iRecord) { if (!manager.isDistributedConfiguration()) return; + OLogManager.instance().info( + this, + ""Caught change "" + iType + "" in database '"" + iRecord.getDatabase().getName() + ""', record: "" + iRecord.getIdentity() + + "". Distribute the change in all the cluster nodes""); + switch (iType) { case AFTER_CREATE: - manager.distributeRequest(connection, new OTransactionEntry>((ORecordInternal) iRecord, - OTransactionEntry.CREATED, null)); + manager.distributeRequest(new OTransactionEntry>((ORecordInternal) iRecord, OTransactionEntry.CREATED, + null)); break; case AFTER_UPDATE: - manager.distributeRequest(connection, new OTransactionEntry>((ORecordInternal) iRecord, - OTransactionEntry.UPDATED, null)); + manager.distributeRequest(new OTransactionEntry>((ORecordInternal) iRecord, OTransactionEntry.UPDATED, + null)); break; case AFTER_DELETE: - manager.distributeRequest(connection, new OTransactionEntry>((ORecordInternal) iRecord, - OTransactionEntry.DELETED, null)); + manager.distributeRequest(new OTransactionEntry>((ORecordInternal) iRecord, OTransactionEntry.DELETED, + null)); break; default: // NOT DISTRIBUTED REQUEST, JUST RETURN return; } + } + + /** + * Install the itself as trigger to catch all the events against records + */ + public void onOpen(final ODatabase iDatabase) { + ((ODatabaseComplex) iDatabase).registerHook(this); + } - System.out.println(""\nCatched update to database: "" + iType + "" record: "" + iRecord); + /** + * Remove itself as trigger to catch all the events against records + */ + public void onClose(final ODatabase iDatabase) { + ((ODatabaseComplex) iDatabase).unregisterHook(this); } } diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java index fe7f6dbedaa..33fb84a9357 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java +++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java @@ -21,7 +21,6 @@ import java.net.SocketException; import java.util.Collection; import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.Set; @@ -70,7 +69,7 @@ import com.orientechnologies.orient.server.OServer; import com.orientechnologies.orient.server.OServerMain; import com.orientechnologies.orient.server.config.OServerUserConfiguration; -import com.orientechnologies.orient.server.handler.OServerHandler; +import com.orientechnologies.orient.server.handler.OServerHandlerHelper; import com.orientechnologies.orient.server.network.protocol.ONetworkProtocol; import com.orientechnologies.orient.server.tx.OTransactionOptimisticProxy; import com.orientechnologies.orient.server.tx.OTransactionRecordProxy; @@ -120,20 +119,24 @@ protected void execute() throws Exception { data.lastCommandReceived = System.currentTimeMillis(); - invokeHandlerCallbackOnBeforeClientRequest((byte) requestType); + OServerHandlerHelper.invokeHandlerCallbackOnBeforeClientRequest(connection, (byte) requestType); parseCommand(); - invokeHandlerCallbackOnAfterClientRequest((byte) requestType); + OServerHandlerHelper.invokeHandlerCallbackOnAfterClientRequest(connection, (byte) requestType); } catch (EOFException eof) { + OServerHandlerHelper.invokeHandlerCallbackOnClientError(connection, eof); sendShutdown(); } catch (SocketException e) { + OServerHandlerHelper.invokeHandlerCallbackOnClientError(connection, e); sendShutdown(); } catch (OException e) { + OServerHandlerHelper.invokeHandlerCallbackOnClientError(connection, e); channel.clearInput(); sendError(clientTxId, e); } catch (Throwable t) { + OServerHandlerHelper.invokeHandlerCallbackOnClientError(connection, t); OLogManager.instance().error(this, ""Error on executing request"", t); channel.clearInput(); sendError(clientTxId, t); @@ -679,7 +682,7 @@ else if (iLinked instanceof Map) @Override public void startup() { - invokeHandlerCallbackOnClientDisconnection(); + OServerHandlerHelper.invokeHandlerCallbackOnClientConnection(connection); } @Override @@ -687,7 +690,7 @@ public void shutdown() { sendShutdown(); channel.close(); - invokeHandlerCallbackOnClientDisconnection(); + OServerHandlerHelper.invokeHandlerCallbackOnClientDisconnection(connection); OClientConnectionManager.instance().onClientDisconnection(connection.id); } @@ -780,46 +783,6 @@ private void writeRecord(final ORecordInternal iRecord) throws IOException { } } - private void invokeHandlerCallbackOnClientConnection() { - final List handlers = OServerMain.server().getHandlers(); - if (handlers != null) - for (OServerHandler handler : handlers) { - handler.onClientConnection(connection); - } - } - - private void invokeHandlerCallbackOnClientDisconnection() { - final List handlers = OServerMain.server().getHandlers(); - if (handlers != null) - for (OServerHandler handler : handlers) { - handler.onClientDisconnection(connection); - } - } - - private void invokeHandlerCallbackOnBeforeClientRequest(final byte iRequestType) { - final List handlers = OServerMain.server().getHandlers(); - if (handlers != null) - for (OServerHandler handler : handlers) { - handler.onBeforeClientRequest(connection, iRequestType); - } - } - - private void invokeHandlerCallbackOnAfterClientRequest(final byte iRequestType) { - final List handlers = OServerMain.server().getHandlers(); - if (handlers != null) - for (OServerHandler handler : handlers) { - handler.onAfterClientRequest(connection, iRequestType); - } - } - - private void invokeHandlerCallbackOnClientError() { - final List handlers = OServerMain.server().getHandlers(); - if (handlers != null) - for (OServerHandler handler : handlers) { - handler.onClientError(connection); - } - } - protected ODatabaseDocumentTx openDatabase(final String dbName, final String iUser, final String iPassword) { // SEARCH THE DB IN MEMORY FIRST ODatabaseDocumentTx db = (ODatabaseDocumentTx) OServerMain.server().getMemoryDatabases().get(dbName); @@ -853,8 +816,6 @@ protected void createDatabase(final ODatabaseDocumentTx iDatabase) { } underlyingDatabase = ((ODatabaseRaw) ((ODatabaseComplex) iDatabase.getUnderlying()).getUnderlying()); - - invokeHandlerCallbackOnClientConnection(); } protected ODatabaseDocumentTx getDatabaseInstance(final String iDbName, final String iStorageMode) { diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/distributed/ONetworkProtocolDistributed.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/distributed/ONetworkProtocolDistributed.java index bf8cd470dd1..6bbaa7bfd48 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/distributed/ONetworkProtocolDistributed.java +++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/distributed/ONetworkProtocolDistributed.java @@ -20,20 +20,16 @@ import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.command.OCommandOutputListener; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.db.tool.ODatabaseExport; import com.orientechnologies.orient.core.db.tool.ODatabaseImport; import com.orientechnologies.orient.core.exception.OConfigurationException; import com.orientechnologies.orient.core.metadata.security.OUser; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.storage.impl.local.OStorageLocal; import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryInputStream; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryOutputStream; import com.orientechnologies.orient.enterprise.channel.distributed.OChannelDistributedProtocol; import com.orientechnologies.orient.server.OServerMain; import com.orientechnologies.orient.server.handler.distributed.ODistributedServerManager; import com.orientechnologies.orient.server.handler.distributed.ODistributedServerNode; -import com.orientechnologies.orient.server.handler.distributed.ODistributedServerNode.STATUS; -import com.orientechnologies.orient.server.handler.distributed.ODistributedSynchronizationException; import com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary; /** @@ -88,6 +84,7 @@ protected void parseCommand() throws IOException { final String dbUser = channel.readString(); final String dbPassword = channel.readString(); final String remoteServerName = channel.readString(); + final String mode = channel.readString(); checkServerAccess(""database.share""); @@ -96,34 +93,8 @@ protected void parseCommand() throws IOException { final String engineName = db.getStorage() instanceof OStorageLocal ? ""local"" : ""memory""; final ODistributedServerNode remoteServerNode = manager.getNode(remoteServerName); - if (remoteServerNode.getStatus() == STATUS.DISCONNECTED) - throw new ODistributedSynchronizationException(""Can't share database '"" + dbName + ""' on remote server node '"" - + remoteServerName + ""' because is disconnected""); - try { - remoteServerNode.channel.acquireExclusiveLock(); - - OLogManager.instance().info(this, ""Sharing database '"" + dbName + ""' to remote server "" + remoteServerName + ""...""); - - // EXECUTE THE REQUEST ON REMOTE SERVER NODE - remoteServerNode.channel.writeByte(OChannelDistributedProtocol.REQUEST_DISTRIBUTED_DB_SHARE_RECEIVER); - remoteServerNode.channel.writeInt(0); - remoteServerNode.channel.writeString(dbName); - remoteServerNode.channel.writeString(engineName); - - OLogManager.instance().info(this, ""Exporting database '%s' via streaming to remote server node: %s..."", dbName, - remoteServerName); - - // START THE EXPORT GIVING AS OUTPUTSTREAM THE CHANNEL TO STREAM THE EXPORT - new ODatabaseExport(db, new OChannelBinaryOutputStream(remoteServerNode.channel), this).exportDatabase(); - - OLogManager.instance().info(this, ""Database exported correctly""); - - remoteServerNode.channel.readStatus(); - - } finally { - remoteServerNode.channel.releaseExclusiveLock(); - } + remoteServerNode.shareDatabase(db, remoteServerName, engineName, mode); sendOk(0); diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/ONetworkProtocolHttpAbstract.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/ONetworkProtocolHttpAbstract.java index 2eb8225aaba..f2d4a6a2e9c 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/ONetworkProtocolHttpAbstract.java +++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/ONetworkProtocolHttpAbstract.java @@ -44,6 +44,7 @@ import com.orientechnologies.orient.server.OClientConnectionManager; import com.orientechnologies.orient.server.OServer; import com.orientechnologies.orient.server.config.OServerConfiguration; +import com.orientechnologies.orient.server.handler.OServerHandlerHelper; import com.orientechnologies.orient.server.network.protocol.ONetworkProtocol; import com.orientechnologies.orient.server.network.protocol.http.command.OServerCommand; @@ -120,10 +121,15 @@ public void service() throws ONetworkProtocolException, IOException { if (cmd != null) try { + OServerHandlerHelper.invokeHandlerCallbackOnBeforeClientRequest(connection, cmd); + if (cmd.beforeExecute(request)) { // EXECUTE THE COMMAND cmd.execute(request); } + + OServerHandlerHelper.invokeHandlerCallbackOnAfterClientRequest(connection, cmd); + } catch (Exception e) { handleError(e); }" 4f4829ba44ea261c80e6d7971be664c157b48e9b,Valadoc,"Embedded: Search images relative to the file ",a,https://github.com/GNOME/vala/,"diff --git a/src/libvaladoc/content/blockcontent.vala b/src/libvaladoc/content/blockcontent.vala index e466177978..d3d8a984ab 100755 --- a/src/libvaladoc/content/blockcontent.vala +++ b/src/libvaladoc/content/blockcontent.vala @@ -1,6 +1,7 @@ /* blockcontent.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -34,9 +35,9 @@ public abstract class Valadoc.Content.BlockContent : ContentElement { public override void configure (Settings settings, ResourceLocator locator) { } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { foreach (Block element in _content) { - element.check (api_root, container, reporter, settings); + element.check (api_root, container, file_path, reporter, settings); } } diff --git a/src/libvaladoc/content/comment.vala b/src/libvaladoc/content/comment.vala index 6978b8f117..0c6f4496fe 100755 --- a/src/libvaladoc/content/comment.vala +++ b/src/libvaladoc/content/comment.vala @@ -1,6 +1,7 @@ /* comment.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -36,11 +37,11 @@ public class Valadoc.Content.Comment : BlockContent { public override void configure (Settings settings, ResourceLocator locator) { } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { - base.check (api_root, container, reporter, settings); + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { + base.check (api_root, container, file_path, reporter, settings); foreach (Taglet element in _taglets) { - element.check (api_root, container, reporter, settings); + element.check (api_root, container, file_path, reporter, settings); } } diff --git a/src/libvaladoc/content/contentelement.vala b/src/libvaladoc/content/contentelement.vala index 427cf66071..be15e5bbdd 100755 --- a/src/libvaladoc/content/contentelement.vala +++ b/src/libvaladoc/content/contentelement.vala @@ -1,6 +1,7 @@ /* contentelement.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -28,7 +29,7 @@ public abstract class Valadoc.Content.ContentElement : Object { public virtual void configure (Settings settings, ResourceLocator locator) { } - public abstract void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings); + public abstract void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings); public abstract void accept (ContentVisitor visitor); diff --git a/src/libvaladoc/content/contentfactory.vala b/src/libvaladoc/content/contentfactory.vala index 19cf41be21..dda8a87636 100755 --- a/src/libvaladoc/content/contentfactory.vala +++ b/src/libvaladoc/content/contentfactory.vala @@ -1,6 +1,7 @@ /* contentfactory.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public diff --git a/src/libvaladoc/content/contentvisitor.vala b/src/libvaladoc/content/contentvisitor.vala index 3eb3a4b3d4..d1b14c4538 100755 --- a/src/libvaladoc/content/contentvisitor.vala +++ b/src/libvaladoc/content/contentvisitor.vala @@ -1,6 +1,7 @@ /* contentvisitor.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public diff --git a/src/libvaladoc/content/embedded.vala b/src/libvaladoc/content/embedded.vala index f158800aae..b8f4222589 100755 --- a/src/libvaladoc/content/embedded.vala +++ b/src/libvaladoc/content/embedded.vala @@ -1,6 +1,7 @@ /* embedded.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -42,7 +43,18 @@ public class Valadoc.Content.Embedded : ContentElement, Inline, StyleAttributes _locator = locator; } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { + // search relative to our file + if (!Path.is_absolute (url)) { + string relative_to_file = Path.build_path (Path.DIR_SEPARATOR_S, Path.get_dirname (file_path), url); + if (FileUtils.test (relative_to_file, FileTest.EXISTS | FileTest.IS_REGULAR)) { + url = (owned) relative_to_file; + package = container.package; + return ; + } + } + + // search relative to the current directory / absoulte path if (!FileUtils.test (url, FileTest.EXISTS | FileTest.IS_REGULAR)) { reporter.simple_error (""%s does not exist"", url); } else { diff --git a/src/libvaladoc/content/headline.vala b/src/libvaladoc/content/headline.vala index c7fcb29ce9..36b19c23b0 100755 --- a/src/libvaladoc/content/headline.vala +++ b/src/libvaladoc/content/headline.vala @@ -1,6 +1,7 @@ /* headline.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -31,12 +32,12 @@ public class Valadoc.Content.Headline : Block, InlineContent { _level = 0; } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { // TODO report error if level == 0 ? // TODO: content.size == 0? // Check inline content - base.check (api_root, container, reporter, settings); + base.check (api_root, container, file_path, reporter, settings); } public override void accept (ContentVisitor visitor) { diff --git a/src/libvaladoc/content/inlinecontent.vala b/src/libvaladoc/content/inlinecontent.vala index 389c66b96b..119f0569d8 100755 --- a/src/libvaladoc/content/inlinecontent.vala +++ b/src/libvaladoc/content/inlinecontent.vala @@ -1,6 +1,7 @@ /* inlinecontent.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -35,9 +36,9 @@ public abstract class Valadoc.Content.InlineContent : ContentElement { internal InlineContent () { } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { foreach (Inline element in _content) { - element.check (api_root, container, reporter, settings); + element.check (api_root, container, file_path, reporter, settings); } } diff --git a/src/libvaladoc/content/inlinetaglet.vala b/src/libvaladoc/content/inlinetaglet.vala index 813bcf3390..151395095f 100755 --- a/src/libvaladoc/content/inlinetaglet.vala +++ b/src/libvaladoc/content/inlinetaglet.vala @@ -1,6 +1,7 @@ /* taglet.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -48,9 +49,9 @@ public abstract class Valadoc.Content.InlineTaglet : ContentElement, Taglet, Inl this.locator = locator; } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { ContentElement element = get_content (); - element.check (api_root, container, reporter, settings); + element.check (api_root, container, file_path, reporter, settings); } public override void accept (ContentVisitor visitor) { diff --git a/src/libvaladoc/content/link.vala b/src/libvaladoc/content/link.vala index e114e96947..e2648981ad 100755 --- a/src/libvaladoc/content/link.vala +++ b/src/libvaladoc/content/link.vala @@ -1,6 +1,7 @@ /* link.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -33,7 +34,7 @@ public class Valadoc.Content.Link : InlineContent, Inline { public override void configure (Settings settings, ResourceLocator locator) { } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { //TODO: check url } diff --git a/src/libvaladoc/content/list.vala b/src/libvaladoc/content/list.vala index c7bae59a85..e55489fe1e 100755 --- a/src/libvaladoc/content/list.vala +++ b/src/libvaladoc/content/list.vala @@ -1,6 +1,7 @@ /* list.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -108,10 +109,10 @@ public class Valadoc.Content.List : ContentElement, Block { _items = new ArrayList (); } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { // Check individual list items foreach (ListItem element in _items) { - element.check (api_root, container, reporter, settings); + element.check (api_root, container, file_path, reporter, settings); } } diff --git a/src/libvaladoc/content/listitem.vala b/src/libvaladoc/content/listitem.vala index f6907964e8..ef5f589f7c 100755 --- a/src/libvaladoc/content/listitem.vala +++ b/src/libvaladoc/content/listitem.vala @@ -1,6 +1,7 @@ /* listitem.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -30,12 +31,12 @@ public class Valadoc.Content.ListItem : InlineContent { base (); } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { // Check inline content - base.check (api_root, container, reporter, settings); + base.check (api_root, container, file_path, reporter, settings); if (sub_list != null) { - sub_list.check (api_root, container, reporter, settings); + sub_list.check (api_root, container, file_path, reporter, settings); } } diff --git a/src/libvaladoc/content/note.vala b/src/libvaladoc/content/note.vala index d2b16c557c..40bb930198 100755 --- a/src/libvaladoc/content/note.vala +++ b/src/libvaladoc/content/note.vala @@ -1,6 +1,7 @@ /* note.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -28,9 +29,9 @@ public class Valadoc.Content.Note : BlockContent, Block { base (); } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { // Check inline content - base.check (api_root, container, reporter, settings); + base.check (api_root, container, file_path, reporter, settings); } public override void accept (ContentVisitor visitor) { diff --git a/src/libvaladoc/content/paragraph.vala b/src/libvaladoc/content/paragraph.vala index 8f89b48b37..4998952d40 100755 --- a/src/libvaladoc/content/paragraph.vala +++ b/src/libvaladoc/content/paragraph.vala @@ -1,6 +1,7 @@ /* paragraph.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -32,9 +33,9 @@ public class Valadoc.Content.Paragraph : InlineContent, Block, StyleAttributes { base (); } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { // Check inline content - base.check (api_root, container, reporter, settings); + base.check (api_root, container, file_path, reporter, settings); } public override void accept (ContentVisitor visitor) { diff --git a/src/libvaladoc/content/run.vala b/src/libvaladoc/content/run.vala index 519b424fe2..146d9c29e2 100755 --- a/src/libvaladoc/content/run.vala +++ b/src/libvaladoc/content/run.vala @@ -1,6 +1,7 @@ /* run.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -117,9 +118,9 @@ public class Valadoc.Content.Run : InlineContent, Inline { _style = style; } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { // Check inline content - base.check (api_root, container, reporter, settings); + base.check (api_root, container, file_path, reporter, settings); } public override void accept (ContentVisitor visitor) { diff --git a/src/libvaladoc/content/sourcecode.vala b/src/libvaladoc/content/sourcecode.vala index fb2bd625e9..338d23b24f 100755 --- a/src/libvaladoc/content/sourcecode.vala +++ b/src/libvaladoc/content/sourcecode.vala @@ -1,6 +1,7 @@ /* sourcecode.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -64,7 +65,7 @@ public class Valadoc.Content.SourceCode : ContentElement, Inline{ _language = Language.VALA; } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { } public override void accept (ContentVisitor visitor) { diff --git a/src/libvaladoc/content/symbollink.vala b/src/libvaladoc/content/symbollink.vala index ef52b30101..aff9476e26 100755 --- a/src/libvaladoc/content/symbollink.vala +++ b/src/libvaladoc/content/symbollink.vala @@ -1,6 +1,7 @@ /* symbollink.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -36,7 +37,7 @@ public class Valadoc.Content.SymbolLink : ContentElement, Inline { public override void configure (Settings settings, ResourceLocator locator) { } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { } public override void accept (ContentVisitor visitor) { diff --git a/src/libvaladoc/content/table.vala b/src/libvaladoc/content/table.vala index dc232ae208..17fa589e8b 100755 --- a/src/libvaladoc/content/table.vala +++ b/src/libvaladoc/content/table.vala @@ -1,6 +1,7 @@ /* table.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -33,12 +34,12 @@ public class Valadoc.Content.Table : ContentElement, Block { _rows = new ArrayList (); } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { // Check the table consistency in term of row/column number // Check individual rows foreach (var row in _rows) { - row.check (api_root, container, reporter, settings); + row.check (api_root, container, file_path, reporter, settings); } } diff --git a/src/libvaladoc/content/tablecell.vala b/src/libvaladoc/content/tablecell.vala index 01e732f090..733aad1ca6 100755 --- a/src/libvaladoc/content/tablecell.vala +++ b/src/libvaladoc/content/tablecell.vala @@ -1,6 +1,7 @@ /* tablecell.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -36,9 +37,9 @@ public class Valadoc.Content.TableCell : InlineContent, StyleAttributes { _rowspan = 1; } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { // Check inline content - base.check (api_root, container, reporter, settings); + base.check (api_root, container, file_path, reporter, settings); } public override void accept (ContentVisitor visitor) { diff --git a/src/libvaladoc/content/tablerow.vala b/src/libvaladoc/content/tablerow.vala index 943c95f646..5cd59fd4bb 100755 --- a/src/libvaladoc/content/tablerow.vala +++ b/src/libvaladoc/content/tablerow.vala @@ -1,6 +1,7 @@ /* tablerow.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -33,10 +34,10 @@ public class Valadoc.Content.TableRow : ContentElement { _cells = new ArrayList (); } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { // Check individual cells foreach (var cell in _cells) { - cell.check (api_root, container, reporter, settings); + cell.check (api_root, container, file_path, reporter, settings); } } diff --git a/src/libvaladoc/content/text.vala b/src/libvaladoc/content/text.vala index 2b147235d5..6d3877e87e 100755 --- a/src/libvaladoc/content/text.vala +++ b/src/libvaladoc/content/text.vala @@ -1,6 +1,7 @@ /* text.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -36,7 +37,7 @@ public class Valadoc.Content.Text : ContentElement, Inline { } } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { } public override void accept (ContentVisitor visitor) { diff --git a/src/libvaladoc/content/warning.vala b/src/libvaladoc/content/warning.vala index e848c43f30..3ab9b3c736 100755 --- a/src/libvaladoc/content/warning.vala +++ b/src/libvaladoc/content/warning.vala @@ -1,6 +1,7 @@ /* warning.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -28,9 +29,9 @@ public class Valadoc.Content.Warning : BlockContent, Block { base (); } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { // Check inline content - base.check (api_root, container, reporter, settings); + base.check (api_root, container, file_path, reporter, settings); } public override void accept (ContentVisitor visitor) { diff --git a/src/libvaladoc/content/wikilink.vala b/src/libvaladoc/content/wikilink.vala index e88bc18f71..e08719f6ab 100755 --- a/src/libvaladoc/content/wikilink.vala +++ b/src/libvaladoc/content/wikilink.vala @@ -1,6 +1,7 @@ /* link.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -34,7 +35,7 @@ public class Valadoc.Content.WikiLink : InlineContent, Inline { public override void configure (Settings settings, ResourceLocator locator) { } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { page = api_root.wikitree.search (name); if (page == null) { reporter.simple_warning (""%s does not exist"".printf (name)); diff --git a/src/libvaladoc/documentation/documentationparser.vala b/src/libvaladoc/documentation/documentationparser.vala index f4a9667cd1..5fa736a5a6 100755 --- a/src/libvaladoc/documentation/documentationparser.vala +++ b/src/libvaladoc/documentation/documentationparser.vala @@ -1,6 +1,7 @@ /* documentationparser.vala * - * Copyright (C) 2008-2011 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -76,7 +77,7 @@ public class Valadoc.DocumentationParser : Object, ResourceLocator { public Comment? parse_comment_str (Api.Node element, string content, string filename, int first_line, int first_column) { try { Comment doc_comment = parse_comment (content, filename, first_line, first_column); - doc_comment.check (_tree, element, _reporter, _settings); + doc_comment.check (_tree, element, filename, _reporter, _settings); return doc_comment; } catch (ParserError error) { return null; @@ -94,7 +95,7 @@ public class Valadoc.DocumentationParser : Object, ResourceLocator { try { Page documentation = parse_wiki (page.documentation_str, page.get_filename ()); - documentation.check (_tree, pkg, _reporter, _settings); + documentation.check (_tree, pkg, page.path, _reporter, _settings); return documentation; } catch (ParserError error) { return null; diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala index 574e65fabb..b1486069d4 100644 --- a/src/libvaladoc/documentation/gtkdoccommentparser.vala +++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala @@ -1,6 +1,6 @@ /* gtkcommentparser.vala * - * Copyright (C) 2011 Florian Brosch + * Copyright (C) 2011-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -260,7 +260,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { first = false; } - comment.check (tree, element, reporter, settings); + comment.check (tree, element, gir_comment.file.relative_path, reporter, settings); return comment; } diff --git a/src/libvaladoc/taglets/tagletdeprecated.vala b/src/libvaladoc/taglets/tagletdeprecated.vala index f51adc174f..468f6ec55f 100755 --- a/src/libvaladoc/taglets/tagletdeprecated.vala +++ b/src/libvaladoc/taglets/tagletdeprecated.vala @@ -1,6 +1,7 @@ /* tagletdeprecated.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -28,8 +29,8 @@ public class Valadoc.Taglets.Deprecated : InlineContent, Taglet, Block { return run_rule; } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { - base.check (api_root, container, reporter, settings); + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { + base.check (api_root, container, file_path, reporter, settings); } public override void accept (ContentVisitor visitor) { diff --git a/src/libvaladoc/taglets/tagletinheritdoc.vala b/src/libvaladoc/taglets/tagletinheritdoc.vala index 329db68696..653a448a10 100755 --- a/src/libvaladoc/taglets/tagletinheritdoc.vala +++ b/src/libvaladoc/taglets/tagletinheritdoc.vala @@ -1,6 +1,7 @@ /* tagletinheritdoc.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -30,7 +31,7 @@ public class Valadoc.Taglets.InheritDoc : InlineTaglet { return null; } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { // TODO Check that the container is an override of an abstract symbol // Also retrieve that abstract symbol _inherited diff --git a/src/libvaladoc/taglets/tagletlink.vala b/src/libvaladoc/taglets/tagletlink.vala index 3ebb6de3eb..cbe8dc499e 100755 --- a/src/libvaladoc/taglets/tagletlink.vala +++ b/src/libvaladoc/taglets/tagletlink.vala @@ -1,6 +1,7 @@ /* taglet.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -50,7 +51,7 @@ public class Valadoc.Taglets.Link : InlineTaglet { }); } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { if (symbol_name.has_prefix (""c::"")) { _symbol_name = _symbol_name.substring (3); _symbol = api_root.search_symbol_cstr (container, symbol_name); @@ -75,7 +76,7 @@ public class Valadoc.Taglets.Link : InlineTaglet { reporter.simple_warning (""%s: %s does not exist"", container.get_full_name (), symbol_name); } - base.check (api_root, container, reporter, settings); + base.check (api_root, container, file_path, reporter, settings); } public override ContentElement produce_content () { diff --git a/src/libvaladoc/taglets/tagletparam.vala b/src/libvaladoc/taglets/tagletparam.vala index 6dfb235ef2..bbff4030b5 100755 --- a/src/libvaladoc/taglets/tagletparam.vala +++ b/src/libvaladoc/taglets/tagletparam.vala @@ -1,6 +1,7 @@ /* taglet.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -40,7 +41,7 @@ public class Valadoc.Taglets.Param : InlineContent, Taglet, Block { } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { // Check for the existence of such a parameter this.parameter = null; @@ -72,7 +73,7 @@ public class Valadoc.Taglets.Param : InlineContent, Taglet, Block { reporter.simple_warning (""%s: Unknown parameter `%s'"", container.get_full_name (), parameter_name); } - base.check (api_root, container, reporter, settings); + base.check (api_root, container, file_path, reporter, settings); } public override void accept (ContentVisitor visitor) { diff --git a/src/libvaladoc/taglets/tagletreturn.vala b/src/libvaladoc/taglets/tagletreturn.vala index a4beee0c6a..5a2797737c 100755 --- a/src/libvaladoc/taglets/tagletreturn.vala +++ b/src/libvaladoc/taglets/tagletreturn.vala @@ -1,6 +1,7 @@ /* taglet.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -29,10 +30,10 @@ public class Valadoc.Taglets.Return : InlineContent, Taglet, Block { return run_rule; } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { // TODO check for the existence of a return type - base.check (api_root, container, reporter, settings); + base.check (api_root, container, file_path, reporter, settings); } public override void accept (ContentVisitor visitor) { diff --git a/src/libvaladoc/taglets/tagletsee.vala b/src/libvaladoc/taglets/tagletsee.vala index 68ed636ed6..895e3c2a22 100755 --- a/src/libvaladoc/taglets/tagletsee.vala +++ b/src/libvaladoc/taglets/tagletsee.vala @@ -1,6 +1,7 @@ /* tagletsee.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -38,7 +39,7 @@ public class Valadoc.Taglets.See : ContentElement, Taglet, Block { }); } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { if (symbol_name.has_prefix (""c::"")) { symbol_name = symbol_name.substring (3); symbol = api_root.search_symbol_cstr (container, symbol_name); diff --git a/src/libvaladoc/taglets/tagletsince.vala b/src/libvaladoc/taglets/tagletsince.vala index 5b68ecfe82..49acafbc0d 100755 --- a/src/libvaladoc/taglets/tagletsince.vala +++ b/src/libvaladoc/taglets/tagletsince.vala @@ -1,6 +1,7 @@ /* tagletsince.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -37,7 +38,7 @@ public class Valadoc.Taglets.Since : ContentElement, Taglet, Block { }); } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { } public override void accept (ContentVisitor visitor) { diff --git a/src/libvaladoc/taglets/tagletthrows.vala b/src/libvaladoc/taglets/tagletthrows.vala index b592f6ca1e..547fbc7ca6 100755 --- a/src/libvaladoc/taglets/tagletthrows.vala +++ b/src/libvaladoc/taglets/tagletthrows.vala @@ -1,6 +1,7 @@ /* tagletthrows.vala * - * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * Copyright (C) 2008-2009 Didier Villevalois + * Copyright (C) 2008-2012 Florian Brosch * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -35,14 +36,14 @@ public class Valadoc.Taglets.Throws : InlineContent, Taglet, Block { }); } - public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { error_domain = api_root.search_symbol_str (container, error_domain_name); if (error_domain == null) { // TODO use ContentElement's source reference reporter.simple_error (""%s does not exist"", error_domain_name); } - base.check (api_root, container, reporter, settings); + base.check (api_root, container, file_path, reporter, settings); } public override void accept (ContentVisitor visitor) {" 1ec7b1afab5fd7c98cda53520c46eeec884fb672,Vala,"gdk-2.0: update to 2.18.6 Fixes bug 609293. ",a,https://github.com/GNOME/vala/,"diff --git a/vapi/gdk-2.0.vapi b/vapi/gdk-2.0.vapi index efe8e7e811..332b11eb01 100644 --- a/vapi/gdk-2.0.vapi +++ b/vapi/gdk-2.0.vapi @@ -90,7 +90,12 @@ namespace Gdk { public weak Gdk.Device core_pointer; public uint double_click_distance; public uint double_click_time; + public uint ignore_core_events; + public weak Gdk.KeyboardGrabInfo keyboard_grab; + public uint32 last_event_time; + public weak GLib.List pointer_grabs; public weak Gdk.DisplayPointerHooks pointer_hooks; + public weak Gdk.PointerWindowInfo pointer_info; public weak GLib.List queued_events; public weak GLib.List queued_tail; public void add_client_message_filter (Gdk.Atom message_type, Gdk.FilterFunc func); @@ -170,6 +175,8 @@ namespace Gdk { public class Drawable : GLib.Object { public unowned Gdk.Image copy_to_image (Gdk.Image image, int src_x, int src_y, int dest_x, int dest_y, int width, int height); [NoWrapper] + public virtual unowned Cairo.Surface create_cairo_surface (int width, int height); + [NoWrapper] public virtual unowned Gdk.GC create_gc (Gdk.GCValues values, Gdk.GCValuesMask mask); [CCode (cname = ""gdk_draw_arc"")] public virtual void draw_arc (Gdk.GC gc, bool filled, int x, int y, int width, int height, int angle1, int angle2); @@ -208,10 +215,14 @@ namespace Gdk { public virtual unowned Gdk.Image get_image (int x, int y, int width, int height); public virtual unowned Gdk.Screen get_screen (); public virtual void get_size (out int width, out int height); + [NoWrapper] + public virtual unowned Gdk.Drawable get_source_drawable (); public virtual unowned Gdk.Region get_visible_region (); public virtual unowned Gdk.Visual get_visual (); [NoWrapper] public virtual unowned Cairo.Surface ref_cairo_surface (); + [NoWrapper] + public virtual void set_cairo_clip (Cairo.Context cr); public virtual void set_colormap (Gdk.Colormap colormap); } [Compact] @@ -244,7 +255,6 @@ namespace Gdk { public static unowned Gdk.Event @get (); public bool get_axis (Gdk.AxisUse axis_use, out double value); public bool get_coords (out double x_win, out double y_win); - public static unowned Gdk.Event get_graphics_expose (Gdk.Window window); public bool get_root_coords (out double x_root, out double y_root); public unowned Gdk.Screen get_screen (); public bool get_state (out Gdk.ModifierType state); @@ -326,6 +336,16 @@ namespace Gdk { public void put_pixel (int x, int y, uint32 pixel); public void set_colormap (Gdk.Colormap colormap); } + [Compact] + [CCode (cheader_filename = ""gdk/gdk.h"")] + public class KeyboardGrabInfo { + public weak Gdk.Window native_window; + public bool owner_events; + public ulong serial; + public uint32 time; + public weak Gdk.Window window; + public static bool libgtk_only (Gdk.Display display, out unowned Gdk.Window grab_window, bool owner_events); + } [CCode (cheader_filename = ""gdk/gdk.h"")] public class Keymap : GLib.Object { public weak Gdk.Display display; @@ -376,6 +396,17 @@ namespace Gdk { public weak GLib.Callback window_at_pointer; } [Compact] + [CCode (cheader_filename = ""gdk/gdk.h"")] + public class PointerWindowInfo { + public uint32 button; + public ulong motion_hint_serial; + public uint32 state; + public weak Gdk.Window toplevel_under_pointer; + public double toplevel_x; + public double toplevel_y; + public weak Gdk.Window window_under_pointer; + } + [Compact] [CCode (copy_function = ""gdk_region_copy"", free_function = ""gdk_region_destroy"", cheader_filename = ""gdk/gdk.h"")] public class Region { [CCode (has_construct_function = false)] @@ -389,6 +420,7 @@ namespace Gdk { public void offset (int dx, int dy); public bool point_in (int x, int y); public static Gdk.Region polygon (Gdk.Point[] points, Gdk.FillRule fill_rule); + public bool rect_equal (Gdk.Rectangle rectangle); public Gdk.OverlapType rect_in (Gdk.Rectangle rectangle); public static Gdk.Region rectangle (Gdk.Rectangle rectangle); public void shrink (int dx, int dy); @@ -405,6 +437,8 @@ namespace Gdk { public weak Gdk.GC[] exposure_gcs; [CCode (array_length = false)] public weak Gdk.GC[] normal_gcs; + [CCode (array_length = false)] + public weak Gdk.GC[] subwindow_gcs; public void broadcast_client_message (Gdk.Event event); public unowned Gdk.Window get_active_window (); public static unowned Gdk.Screen get_default (); @@ -493,17 +527,21 @@ namespace Gdk { public static void constrain_size (Gdk.Geometry geometry, uint flags, int width, int height, out int new_width, out int new_height); public void deiconify (); public void destroy (); - public void destroy_notify (); public void enable_synchronized_configure (); public void end_paint (); + public bool ensure_native (); + public void flush (); public void focus (uint32 timestamp); public static unowned Gdk.Window foreign_new (Gdk.NativeWindow anid); public static unowned Gdk.Window foreign_new_for_display (Gdk.Display display, Gdk.NativeWindow anid); public void freeze_toplevel_updates_libgtk_only (); public void freeze_updates (); public void fullscreen (); + public void geometry_changed (); public unowned GLib.List get_children (); + public unowned Gdk.Cursor? get_cursor (); public bool get_decorations (out Gdk.WMDecoration decorations); + public bool get_deskrelative_origin (out int x, out int y); public Gdk.EventMask get_events (); public void get_frame_extents (out Gdk.Rectangle rect); public void get_geometry (out int x, out int y, out int width, out int height, out int depth); @@ -513,6 +551,7 @@ namespace Gdk { public unowned Gdk.Window get_parent (); public unowned Gdk.Window get_pointer (out int x, out int y, out Gdk.ModifierType mask); public void get_position (out int x, out int y); + public void get_root_coords (int x, int y, int root_x, int root_y); public void get_root_origin (out int x, out int y); public Gdk.WindowState get_state (); public unowned Gdk.Window get_toplevel (); @@ -527,6 +566,7 @@ namespace Gdk { public void invalidate_maybe_recurse (Gdk.Region region, GLib.Callback child_func); public void invalidate_rect (Gdk.Rectangle? rect, bool invalidate_children); public void invalidate_region (Gdk.Region region, bool invalidate_children); + public bool is_destroyed (); public bool is_viewable (); public bool is_visible (); public static unowned Gdk.Window lookup (Gdk.NativeWindow anid); @@ -547,6 +587,7 @@ namespace Gdk { public void remove_redirection (); public void reparent (Gdk.Window new_parent, int x, int y); public void resize (int width, int height); + public void restack (Gdk.Window sibling, bool above); public void scroll (int dx, int dy); public void set_accept_focus (bool accept_focus); public void set_back_pixmap (Gdk.Pixmap? pixmap, bool parent_relative); @@ -591,6 +632,10 @@ namespace Gdk { public void unmaximize (); public void unstick (); public void withdraw (); + public Gdk.Cursor cursor { get; set; } + public virtual signal void from_embedder (double p0, double p1, void* p2, void* p3); + public virtual signal unowned Gdk.Window pick_embedded_child (double p0, double p1); + public virtual signal void to_embedder (double p0, double p1, void* p2, void* p3); } [CCode (cheader_filename = ""gdk/gdk.h"")] [SimpleType] @@ -1172,7 +1217,8 @@ namespace Gdk { SETTING, OWNER_CHANGE, GRAB_BROKEN, - DAMAGE + DAMAGE, + EVENT_LAST } [CCode (cprefix = ""GDK_EXTENSION_EVENTS_"", cheader_filename = ""gdk/gdk.h"")] public enum ExtensionMode { @@ -1485,7 +1531,8 @@ namespace Gdk { CHILD, DIALOG, TEMP, - FOREIGN + FOREIGN, + OFFSCREEN } [CCode (cprefix = ""GDK_WINDOW_TYPE_HINT_"", cheader_filename = ""gdk/gdk.h"")] public enum WindowTypeHint { @@ -1539,6 +1586,8 @@ namespace Gdk { [CCode (cheader_filename = ""gdk/gdk.h"")] public static void cairo_region (Cairo.Context cr, Gdk.Region region); [CCode (cheader_filename = ""gdk/gdk.h"")] + public static void cairo_reset_clip (Cairo.Context cr, Gdk.Drawable drawable); + [CCode (cheader_filename = ""gdk/gdk.h"")] public static void cairo_set_source_color (Cairo.Context cr, Gdk.Color color); [CCode (cheader_filename = ""gdk/gdk.h"")] public static void cairo_set_source_pixbuf (Cairo.Context cr, Gdk.Pixbuf pixbuf, double pixbuf_x, double pixbuf_y); @@ -1661,8 +1710,6 @@ namespace Gdk { [CCode (cheader_filename = ""gdk/gdk.h"")] public static Gdk.GrabStatus keyboard_grab (Gdk.Window window, bool owner_events, uint32 time_); [CCode (cheader_filename = ""gdk/gdk.h"")] - public static bool keyboard_grab_info_libgtk_only (Gdk.Display display, out unowned Gdk.Window grab_window, bool owner_events); - [CCode (cheader_filename = ""gdk/gdk.h"")] public static void keyboard_ungrab (uint32 time_); [CCode (cheader_filename = ""gdk/gdk.h"")] public static void keyval_convert_case (uint symbol, uint lower, uint upper); @@ -1687,6 +1734,12 @@ namespace Gdk { [CCode (cheader_filename = ""gdk/gdk.h"")] public static void notify_startup_complete_with_id (string startup_id); [CCode (cheader_filename = ""gdk/gdk.h"")] + public static unowned Gdk.Window? offscreen_window_get_embedder (Gdk.Window window); + [CCode (cheader_filename = ""gdk/gdk.h"")] + public static unowned Gdk.Pixmap? offscreen_window_get_pixmap (Gdk.Window window); + [CCode (cheader_filename = ""gdk/gdk.h"")] + public static void offscreen_window_set_embedder (Gdk.Window window, Gdk.Window embedder); + [CCode (cheader_filename = ""gdk/gdk.h"")] public static unowned Pango.Context pango_context_get (); [CCode (cheader_filename = ""gdk/gdk.h"")] public static unowned Pango.Context pango_context_get_for_screen (Gdk.Screen screen); @@ -1753,7 +1806,7 @@ namespace Gdk { [CCode (cheader_filename = ""gdk/gdk.h"")] public static bool selection_owner_set_for_display (Gdk.Display display, Gdk.Window owner, Gdk.Atom selection, uint32 time_, bool send_event); [CCode (cheader_filename = ""gdk/gdk.h"")] - public static bool selection_property_get (Gdk.Window requestor, uchar[] data, Gdk.Atom prop_type, int prop_format); + public static int selection_property_get (Gdk.Window requestor, uchar[] data, Gdk.Atom prop_type, int prop_format); [CCode (cheader_filename = ""gdk/gdk.h"")] public static void selection_send_notify (Gdk.NativeWindow requestor, Gdk.Atom selection, Gdk.Atom target, Gdk.Atom property, uint32 time_); [CCode (cheader_filename = ""gdk/gdk.h"")] @@ -1783,8 +1836,6 @@ namespace Gdk { [CCode (cheader_filename = ""gdk/gdk.h"")] public static int string_to_compound_text_for_display (Gdk.Display display, string str, Gdk.Atom encoding, int format, uchar[] ctext, int length); [CCode (cheader_filename = ""gdk/gdk.h"")] - public static void synthesize_window_state (Gdk.Window window, Gdk.WindowState unset_flags, Gdk.WindowState set_flags); - [CCode (cheader_filename = ""gdk/gdk.h"")] public static void test_render_sync (Gdk.Window window); [CCode (cheader_filename = ""gdk/gdk.h"")] public static bool test_simulate_button (Gdk.Window window, int x, int y, uint button, Gdk.ModifierType modifiers, Gdk.EventType button_pressrelease); diff --git a/vapi/packages/gdk-2.0/gdk-2.0.excludes b/vapi/packages/gdk-2.0/gdk-2.0.excludes index e44260e8fc..9ca941ac4a 100644 --- a/vapi/packages/gdk-2.0/gdk-2.0.excludes +++ b/vapi/packages/gdk-2.0/gdk-2.0.excludes @@ -1,3 +1,6 @@ gdkalias.h gdkkeysyms.h gdkx.h +gdkdirectfb.h +gdkprivate.h +gdkprivate-directfb.h diff --git a/vapi/packages/gdk-2.0/gdk-2.0.gi b/vapi/packages/gdk-2.0/gdk-2.0.gi index e2f5c77807..ed82bd46b4 100644 --- a/vapi/packages/gdk-2.0/gdk-2.0.gi +++ b/vapi/packages/gdk-2.0/gdk-2.0.gi @@ -38,6 +38,13 @@ + + + + + + + @@ -587,14 +594,6 @@ - - - - - - - - @@ -663,6 +662,25 @@ + + + + + + + + + + + + + + + + + + + @@ -921,7 +939,7 @@ - + @@ -1050,14 +1068,6 @@ - - - - - - - - @@ -1523,6 +1533,21 @@ + + + + + + + + + + + + + + + @@ -1576,6 +1601,15 @@ + + + + + + + + + @@ -1651,6 +1685,13 @@ + + + + + + + @@ -1775,35 +1816,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -1969,12 +1981,6 @@ - - - - - - @@ -2305,6 +2311,7 @@ + @@ -2481,6 +2488,7 @@ + @@ -3111,9 +3119,14 @@ + + + + + @@ -3243,6 +3256,14 @@ + + + + + + + + @@ -3279,6 +3300,21 @@ + + + + + + + + + + + + + + + @@ -3469,6 +3505,12 @@ + + + + + + @@ -3487,6 +3529,13 @@ + + + + + + + @@ -4254,6 +4303,7 @@ + @@ -4422,19 +4472,25 @@ - + - + - + + + + + + + @@ -4478,12 +4534,24 @@ + + + + + + + + + + + + @@ -4491,6 +4559,14 @@ + + + + + + + + @@ -4561,6 +4637,16 @@ + + + + + + + + + + @@ -4661,6 +4747,12 @@ + + + + + + @@ -4804,6 +4896,14 @@ + + + + + + + + @@ -5109,6 +5209,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vapi/packages/gdk-2.0/gdk-2.0.metadata b/vapi/packages/gdk-2.0/gdk-2.0.metadata index 261ea0e141..68669dd3ba 100644 --- a/vapi/packages/gdk-2.0/gdk-2.0.metadata +++ b/vapi/packages/gdk-2.0/gdk-2.0.metadata @@ -63,6 +63,8 @@ gdk_keymap_get_entries_for_keycode.keyvals is_array=""1"" is_out=""1"" gdk_keymap_get_entries_for_keyval.keys is_array=""1"" is_out=""1"" GdkKeymapKey is_value_type=""1"" GdkNativeWindow is_value_type=""1"" simple_type=""1"" +gdk_offscreen_window_get_embedder nullable=""1"" +gdk_offscreen_window_get_pixmap nullable=""1"" GdkPangoAttr* is_value_type=""1"" gdk_pixbuf_get_from_drawable.dest nullable=""1"" gdk_pixbuf_get_from_drawable.cmap nullable=""1"" @@ -126,6 +128,7 @@ GdkWindowClass common_prefix=""GDK_"" GdkWindowObject hidden=""1"" GdkWindowObjectClass hidden=""1"" GdkWindowRedirect is_value_type=""1"" +gdk_window_get_cursor nullable=""1"" gdk_window_get_geometry.x is_out=""1"" gdk_window_get_geometry.y is_out=""1"" gdk_window_get_geometry.width is_out=""1""" 494289e5b21e6f48c2ef108f61f1626a3ef9c59e,csemike$oneswarm,"refactor out the abstract class OverlayEndpoint and use it to share functionality between overlaytransport and service connection ",p,https://github.com/csemike/oneswarm,"diff --git a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/OSF2FAzSwtUi.java b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/OSF2FAzSwtUi.java index 1539bbf8..07584769 100644 --- a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/OSF2FAzSwtUi.java +++ b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/OSF2FAzSwtUi.java @@ -31,8 +31,9 @@ import org.gudy.azureus2.ui.swt.plugins.UISWTViewEventListener; import edu.washington.cs.oneswarm.f2f.network.FriendConnection; -import edu.washington.cs.oneswarm.f2f.network.OverlayTransport; import edu.washington.cs.oneswarm.f2f.network.FriendConnection.OverlayForward; +import edu.washington.cs.oneswarm.f2f.network.OverlayEndpoint; +import edu.washington.cs.oneswarm.f2f.network.OverlayTransport; public class OSF2FAzSwtUi { public static final String KEY_OVERLAY_TRANSPORT = ""key_peer_transport""; @@ -220,7 +221,7 @@ public void refresh(TableCell cell) { cell.setText(""""); return; } - OverlayTransport tr = (OverlayTransport) peer.getPEPeer().getData(KEY_OVERLAY_TRANSPORT); + OverlayEndpoint tr = (OverlayEndpoint) peer.getPEPeer().getData(KEY_OVERLAY_TRANSPORT); if (tr == null) { cell.setText(""""); return; @@ -550,9 +551,9 @@ private void addOverlays(FriendConnection sel) { item.setText(new String[] { ""forward"", f.getChannelId() + """", sel.getRemoteFriend().getNick(), sel.getRemoteIp().getHostAddress() + "":"" + sel.getRemotePort(), f.getRemoteFriend().getNick(), f.getRemoteIpPort(), formatter.formatTimeFromSeconds(f.getAge() / 1000), formatter.formatTimeFromSeconds(f.getLastMsgTime() / 1000), formatter.formatByteCountToKiBEtc(f.getBytesForwarded()), formatter.formatByteCountToKiBEtc(f.getBytesForwarded()), f.getSourceMessage().getDescription() }); } - Map transports = sel.getOverlayTransports(); + Map transports = sel.getOverlayTransports(); for (Integer id : transports.keySet()) { - OverlayTransport f = transports.get(id); + OverlayEndpoint f = transports.get(id); TableItem item = new TableItem(overlayConnectionTable, SWT.NONE); item.setText(new String[] { ""transport"", f.getPathID() + """", ""Me"", ""N/A"", sel.getRemoteFriend().getNick(), sel.getRemoteIp().getHostAddress() + "":"" + sel.getRemotePort(), formatter.formatTimeFromSeconds(f.getAge() / 1000), formatter.formatTimeFromSeconds(f.getLastMsgTime() / 1000), formatter.formatByteCountToKiBEtc(f.getBytesIn()), formatter.formatByteCountToKiBEtc(f.getBytesOut()) }); } diff --git a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/OSF2FPlugin.java b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/OSF2FPlugin.java index d712973e..ea8eb383 100644 --- a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/OSF2FPlugin.java +++ b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/OSF2FPlugin.java @@ -42,9 +42,10 @@ import edu.washington.cs.oneswarm.f2f.messaging.OSF2FSearch; import edu.washington.cs.oneswarm.f2f.messaging.OSF2FTextSearch; import edu.washington.cs.oneswarm.f2f.network.FriendConnection; +import edu.washington.cs.oneswarm.f2f.network.FriendConnection.OverlayForward; +import edu.washington.cs.oneswarm.f2f.network.OverlayEndpoint; import edu.washington.cs.oneswarm.f2f.network.OverlayManager; import edu.washington.cs.oneswarm.f2f.network.OverlayTransport; -import edu.washington.cs.oneswarm.f2f.network.FriendConnection.OverlayForward; import edu.washington.cs.oneswarm.f2f.permissions.PermissionsDAO; import edu.washington.cs.oneswarm.plugins.PluginCallback; import edu.washington.cs.publickey.PublicKeyFriend; @@ -605,11 +606,11 @@ public String getDebugInfo() { for (OverlayForward of : overlayForwards.values()) { b.append("" channel="" + Integer.toHexString(of.getChannelId()) + "" "" + of.getRemoteFriend().getNick() + "" lastSent="" + of.getLastMsgTime() + "" src="" + of.getSourceMessage().getDescription() + ""\n""); } - Collection transports = f.getOverlayTransports().values(); + Collection transports = f.getOverlayTransports().values(); if (transports.size() > 0) { b.append("" Transports: \n""); } - for (OverlayTransport ot : transports) { + for (OverlayEndpoint ot : transports) { b.append("" channel="" + Integer.toHexString(ot.getChannelId()) + "" path="" + Integer.toHexString(ot.getPathID()) + "" lastSent="" + ot.getLastMsgTime() + ""\n""); } } diff --git a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/FriendConnection.java b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/FriendConnection.java index 2e8e8eaa..7b5b5c4a 100644 --- a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/FriendConnection.java +++ b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/FriendConnection.java @@ -154,7 +154,7 @@ public class FriendConnection { private final ConcurrentHashMap overlayTransportPathsId = new ConcurrentHashMap(); - private final ConcurrentHashMap overlayTransports = new ConcurrentHashMap(); + private final ConcurrentHashMap overlayTransports = new ConcurrentHashMap(); /* * map to keep track of received searches to avoid sending the search back @@ -447,9 +447,9 @@ public void close() { } // we need to terminate all overlay transports - List transports = new LinkedList( + List transports = new LinkedList( overlayTransports.values()); - for (OverlayTransport overlayTransport : transports) { + for (OverlayEndpoint overlayTransport : transports) { overlayTransport.closeConnectionClosed(""friend closed connection""); } @@ -539,12 +539,12 @@ private void deregisterOverlayForward(int channelId, boolean sendReset) { } - void deregisterOverlayTransport(OverlayTransport transport) { + void deregisterOverlayTransport(OverlayEndpoint transport) { lock.lock(); try { int channelId = transport.getChannelId(); - OverlayTransport exists = overlayTransports.remove(channelId); + OverlayEndpoint exists = overlayTransports.remove(channelId); recentlyClosedChannels.put(channelId, System.currentTimeMillis()); int pathID = transport.getPathID(); overlayTransportPathsId.remove(pathID); @@ -643,7 +643,7 @@ public Map getOverlayForwards() { return overlayForwards; } - public Map getOverlayTransports() { + public Map getOverlayTransports() { return overlayTransports; } @@ -685,7 +685,7 @@ private void handleChannelMsg(Message message) { if (overlayTransports.containsKey(channelId)) { // ok, this is a msg to us - OverlayTransport t = overlayTransports.get(channelId); + OverlayEndpoint t = overlayTransports.get(channelId); msg.setForward(false); // this might we the first message we get in this channel // means that the other side responded to our channel setup @@ -1235,7 +1235,7 @@ void registerOverlayForward(OSF2FSearchResp currentSetupMsg, FriendConnection co } } - void registerOverlayTransport(OverlayTransport transport) throws OverlayRegistrationError { + void registerOverlayTransport(OverlayEndpoint transport) throws OverlayRegistrationError { lock.lock(); try { int channelId = transport.getChannelId(); diff --git a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/OverlayEndpoint.java b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/OverlayEndpoint.java new file mode 100644 index 00000000..d186b29e --- /dev/null +++ b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/OverlayEndpoint.java @@ -0,0 +1,222 @@ +package edu.washington.cs.oneswarm.f2f.network; + +import java.util.TimerTask; +import java.util.logging.Logger; + +import org.gudy.azureus2.core3.util.Average; +import org.gudy.azureus2.core3.util.DirectByteBuffer; + +import com.aelitis.azureus.core.networkmanager.NetworkManager; + +import edu.washington.cs.oneswarm.f2f.Friend; +import edu.washington.cs.oneswarm.f2f.messaging.OSF2FChannelDataMsg; +import edu.washington.cs.oneswarm.f2f.messaging.OSF2FChannelReset; +import edu.washington.cs.oneswarm.f2f.messaging.OSF2FMessage; +import edu.washington.cs.oneswarm.f2f.network.DelayedExecutorService.DelayedExecutor; + +public abstract class OverlayEndpoint { + private final static Logger logger = Logger.getLogger(OverlayEndpoint.class.getName()); + /* + * max number of ms that a message can be delivered earlier than + * overlayDelayMs if that avoids a call to Thread.sleep() + */ + private final static int INCOMING_MESSAGE_DELAY_SLACK = 10; + + protected long bytesIn = 0; + + protected long bytesOut = 0; + protected boolean started = false; + + protected final int channelId; + + protected boolean closed = false; + protected String closeReason = """"; + + private String desc = null; + private final DelayedExecutor delayedOverlayMessageTimer; + + protected Average downloadRateAverage = Average.getInstance(1000, 10); + + protected final FriendConnection friendConnection; + protected long lastMsgTime; + private final long overlayDelayMs; + protected final int pathID; + private boolean sentReset = false; + + private final long startTime; + private final int TIMEOUT = 2 * 60 * 1000; + + protected Average uploadRateAverage = Average.getInstance(1000, 10); + + public OverlayEndpoint(FriendConnection friendConnection, int channelId, int pathID, + long overlayDelayMs) { + this.friendConnection = friendConnection; + this.channelId = channelId; + this.pathID = pathID; + this.overlayDelayMs = overlayDelayMs; + this.lastMsgTime = System.currentTimeMillis(); + this.startTime = System.currentTimeMillis(); + delayedOverlayMessageTimer = DelayedExecutorService.getInstance().getFixedDelayExecutor( + overlayDelayMs); + } + + protected abstract void cleanup(); + + private void deregister() { + // remove it from the friend connection + friendConnection.deregisterOverlayTransport(this); + cleanup(); + } + + /** + * This method is called ""from above"", when the peer connection is + * terminated, send a reset to other side + */ + public void close(String reason) { + if (!closed) { + closeReason = ""peer - "" + reason; + logger.fine(getDescription() + "": OverlayTransport closed, reason:"" + closeReason); + + closed = true; + this.sendReset(); + } + // we don't expect anyone to read whatever we have left in the buffer + this.destroyBufferedMessages(); + + deregister(); + } + + /** + * this method is called from below when a reset is received + * + * @param reason + */ + public void closeChannelReset() { + if (sentReset) { + // ok, this is the response to our previous close + deregister(); + } else { + if (!closed) { + closeReason = ""remote host closed overlay channel""; + logger.fine(getDescription() + "": OverlayTransport closed, reason:"" + closeReason); + // this is the remote side saying that the connection is closed + // send a reset back to confirm + closed = true; + sendReset(); + } + } + } + + /** + * this method is called from below if the friend connection dies + * + * @param reason + */ + public void closeConnectionClosed(String reason) { + closeReason = reason; + logger.fine(getDescription() + "": OverlayTransport closed, reason:"" + closeReason); + + closed = true; + deregister(); + } + + protected abstract void destroyBufferedMessages(); + + public long getAge() { + return System.currentTimeMillis() - startTime; + } + + public long getArtificialDelay() { + return overlayDelayMs; + } + + public long getBytesIn() { + return bytesIn; + } + + public long getBytesOut() { + return bytesOut; + } + + public int getChannelId() { + return channelId; + } + + public String getDescription() { + if (desc == null) { + desc = NetworkManager.OSF2F_TRANSPORT_PREFIX + "": "" + + friendConnection.getRemoteFriend().getNick() + "":"" + + Integer.toHexString(channelId); + } + return desc; + } + + public int getDownloadRate() { + return (int) downloadRateAverage.getAverage(); + } + + public long getLastMsgTime() { + return System.currentTimeMillis() - lastMsgTime; + } + + public int getPathID() { + return pathID; + } + + public Friend getRemoteFriend() { + return friendConnection.getRemoteFriend(); + } + + public String getRemoteIP() { + return friendConnection.getRemoteIp().getHostAddress(); + } + + public int getUploadRate() { + return (int) uploadRateAverage.getAverage(); + } + + protected abstract void handleDelayedOverlayMessage(final OSF2FChannelDataMsg msg); + + public void incomingOverlayMsg(final OSF2FChannelDataMsg msg) { + lastMsgTime = System.currentTimeMillis(); + if (closed) { + return; + } + delayedOverlayMessageTimer.queue(overlayDelayMs, INCOMING_MESSAGE_DELAY_SLACK, + new TimerTask() { + @Override + public void run() { + handleDelayedOverlayMessage(msg); + } + }); + } + + public boolean isLANLocal() { + return friendConnection.getNetworkConnection().isLANLocal(); + } + + public boolean isStarted() { + return started; + } + + public boolean isTimedOut() { + return System.currentTimeMillis() - lastMsgTime > TIMEOUT; + } + + private void sendReset() { + sentReset = true; + friendConnection.sendChannelRst(new OSF2FChannelReset(OSF2FChannelReset.CURRENT_VERSION, + channelId)); + } + + abstract void start(); + + protected long writeMessageToFriendConnection(DirectByteBuffer msgBuffer) { + OSF2FChannelDataMsg msg = new OSF2FChannelDataMsg(OSF2FMessage.CURRENT_VERSION, channelId, + msgBuffer); + long totalWritten = msgBuffer.remaining(DirectByteBuffer.SS_MSG); + msg.setForward(false); + friendConnection.sendChannelMsg(msg, true); + return totalWritten; + } +} diff --git a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/OverlayManager.java b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/OverlayManager.java index f933377c..c6505ad3 100644 --- a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/OverlayManager.java +++ b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/OverlayManager.java @@ -56,837 +56,902 @@ public class OverlayManager { - /** - * make sure to not call any az functions when holding this lock - */ - public static BigFatLock lock = BigFatLock.getInstance(false); - - // private Friend me; - public static boolean logToStdOut = false; - - private int mMIN_DELAY_LINK_LATENCY = COConfigurationManager.getIntParameter(""f2f_search_emulate_hops_min"") * COConfigurationManager.getIntParameter(""f2f_overlay_emulate_link_latency_max""); - private int mMAX_DELAY_LINK_LATENCY = COConfigurationManager.getIntParameter(""f2f_search_emulate_hops_max"") * COConfigurationManager.getIntParameter(""f2f_overlay_emulate_link_latency_max""); - private int mMIN_RESPONSE_DELAY = COConfigurationManager.getIntParameter(""f2f_search_emulate_hops_min"") * COConfigurationManager.getIntParameter(""f2f_search_forward_delay""); - private int mMAX_RESPONSE_DELAY = COConfigurationManager.getIntParameter(""f2f_search_emulate_hops_max"") * COConfigurationManager.getIntParameter(""f2f_search_forward_delay""); - - private double mForwardSearchProbability = COConfigurationManager.getFloatParameter(""f2f_forward_search_probability""); - - // this is just a way to treat requests for the local file list a bit - // differently - public final static int OWN_CONNECTION_ID_MAGIC_NUMBER = 0; - - private final static String RESPONSE_DELAY_SEED_SETTING_KEY = ""response_delay_seed""; - - private static final int TIMEOUT_CHECK_PERIOD = 5 * 1000; - private final ConcurrentHashMap connections; - private final FileListManager filelistManager; - private final LinkedList friendConnectListeners = new LinkedList(); - - private final FriendManager friendManager; - private long lastConnectionCheckRun = System.currentTimeMillis(); - - private final AZInstance myInstance; - private final PublicKey ownPublicKey; - private final QueueManager queueManager = new QueueManager(); - private final RandomnessManager randomnessManager; - private final RandomnessManager responseDelayRandomnesManager; - private final SearchManager searchManager; - - public RotatingLogger searchTimingsLogger = new RotatingLogger(""search_timing""); - - private final GlobalManagerStats stats; - - private boolean stopped = false; - private final Timer t = new Timer(""FriendConnectionInitialChecker"", true); - - public OverlayManager(FriendManager _friendManager, PublicKey _ownPublicKey, FileListManager _fileListManager, GlobalManagerStats _stats) { - stats = _stats; - myInstance = AzureusCoreImpl.getSingleton().getInstanceManager().getMyInstance(); - - this.randomnessManager = new RandomnessManager(); - this.friendManager = _friendManager; - this.filelistManager = _fileListManager; - this.ownPublicKey = _ownPublicKey; - this.connections = new ConcurrentHashMap(); - this.searchManager = new SearchManager(this, filelistManager, randomnessManager, stats); - - byte[] seedBytes = COConfigurationManager.getByteParameter(RESPONSE_DELAY_SEED_SETTING_KEY); - if (seedBytes != null) { - responseDelayRandomnesManager = new RandomnessManager(seedBytes); - } else { - responseDelayRandomnesManager = new RandomnessManager(); - COConfigurationManager.setParameter(RESPONSE_DELAY_SEED_SETTING_KEY, randomnessManager.getSecretBytes()); - } - - COConfigurationManager.addAndFireParameterListeners(new String[] { ""f2f_overlay_emulate_link_latency_max"", - ""f2f_search_emulate_hops_min"", ""f2f_search_emulate_hops_max"", ""f2f_search_forward_delay"", - ""f2f_forward_search_probability"" }, new ParameterListener() { - public void parameterChanged(String parameterName) { - mMIN_DELAY_LINK_LATENCY = COConfigurationManager.getIntParameter(""f2f_search_emulate_hops_min"") * COConfigurationManager.getIntParameter(""f2f_overlay_emulate_link_latency_max""); - mMAX_DELAY_LINK_LATENCY = COConfigurationManager.getIntParameter(""f2f_search_emulate_hops_max"") * COConfigurationManager.getIntParameter(""f2f_overlay_emulate_link_latency_max""); - mMIN_RESPONSE_DELAY = COConfigurationManager.getIntParameter(""f2f_search_emulate_hops_min"") * COConfigurationManager.getIntParameter(""f2f_search_forward_delay""); - mMAX_RESPONSE_DELAY = COConfigurationManager.getIntParameter(""f2f_search_emulate_hops_max"") * COConfigurationManager.getIntParameter(""f2f_search_forward_delay""); - mForwardSearchProbability = COConfigurationManager.getFloatParameter(""f2f_forward_search_probability""); - - if( mForwardSearchProbability <= 0 ) { - COConfigurationManager.setParameter(""f2f_forward_search_probability"", 0.5f); - mForwardSearchProbability = 0.5; - } - System.err.println(""f2f_search_fwd_p: "" + mForwardSearchProbability); - } - }); - - OSF2FMessageFactory.init(); - - Timer timeoutTimer = new Timer(""OS Overlay Timeout checker"", true); - timeoutTimer.schedule(new ConnectionChecker(), 0, TIMEOUT_CHECK_PERIOD); - - } - - public void closeAllConnections() { - for (FriendConnection c : connections.values()) { - c.close(); - } - - stopped = true; - } - - public boolean createIncomingConnection(byte[] publicKey, NetworkConnection netConn) { - - if (isConnectionAllowed(netConn.getEndpoint().getNotionalAddress().getAddress(), publicKey)) { - Friend friend = friendManager.getFriend(publicKey); - new FriendConnection(stats, queueManager, netConn, friend, filelistManager, new FriendConnectionListener()); - - return true; - } - return false; - } - - public boolean createOutgoingConnection(ConnectionEndpoint remoteFriendAddr, Friend friend) { - if (isConnectionAllowed(remoteFriendAddr.getNotionalAddress().getAddress(), friend.getPublicKey())) { - final FriendConnection fc = new FriendConnection(stats, queueManager, remoteFriendAddr, friend, filelistManager, new FriendConnectionListener()); - /* - * create a check for this connection to verify that we actually get - * connected within a reasonable time frame - */ - t.schedule(new TimerTask() { - @Override - public void run() { - if (fc.isTimedOut()) { - fc.close(); - } - } - }, FriendConnection.INITIAL_HANDSHAKE_TIMEOUT + 10 * 1000); - - return true; - } - return false; - } - - private boolean deregisterConnection(FriendConnection connection) { - lock.lock(); - try { - Log.log(""deregistered connection: "" + connection.toString() + "" "" + connections.containsKey(connection.hashCode()) + "" "", logToStdOut); - boolean res = null != connections.remove(connection.hashCode()); - Friend remoteFriend = connection.getRemoteFriend(); - - /* - * check if there are any active connections to the friend, if not, - * mark as disconnected - * - * this check is needed if there are 2 concurrent connections to the - * same friend , and one is denied to register because of the other - * one already connected - */ - - FriendConnection connectedConn = null; - for (FriendConnection c : connections.values()) { - if (c.getRemoteFriend().equals(remoteFriend)) { - connectedConn = c; - } - } - /* - * if the connection id != null, verify that the friend actually - * think it is connected to the right connection id - */ - if (connectedConn != null && connectedConn.isHandshakeReceived()) { - int friendConnId = remoteFriend.getConnectionId(); - if (connectedConn.hashCode() != friendConnId) { - // fix it... - boolean fileListReceived = connectedConn.isFileListReceived(); - if (!fileListReceived) { - Log.log(""connection closed, existing connection found, set to handshaking: "" + remoteFriend.getNick(), logToStdOut); - remoteFriend.setStatus(Friend.STATUS_HANDSHAKING); - remoteFriend.setConnectionId(Friend.NOT_CONNECTED_CONNECTION_ID); - } else { - Log.log(""connection closed, existing connection found, set to connected: "" + remoteFriend.getNick(), logToStdOut); - remoteFriend.setConnectionId(connectedConn.hashCode()); - remoteFriend.setStatus(Friend.STATUS_ONLINE); - } - } - } else { - // ok, no existing connections, mark as disconnected. - remoteFriend.disconnected(connection.hashCode()); - } - - return res; - } finally { - lock.unlock(); - } - } - - public void disconnectFriend(Friend f) { - for (FriendConnection conn : connections.values()) { - if (conn.getRemoteFriend().equals(f)) { - conn.close(); - } - } - } - - void forwardSearchOrCancel(FriendConnection ignoreConn, OSF2FSearch msg) { - for (FriendConnection conn : connections.values()) { - if (ignoreConn.hashCode() == conn.hashCode()) { - Log.log(""not forwarding search/cancel to: "" + conn + "" (source friend)"", logToStdOut); - continue; - } - Log.log(""forwarding search/cancel to: "" + conn, logToStdOut); - if (shouldForwardSearch(msg, ignoreConn)) { - conn.sendSearch(msg.clone(), false); - } - } - } - - public int getConnectCount() { - return connections.size(); - } - - public Map getConnectedFriends() { - // sanity checks - for (int connectionId : connections.keySet()) { - FriendConnection c = connections.get(connectionId); - // check status just to make sure - final Friend remoteFriend = c.getRemoteFriend(); - int status = remoteFriend.getStatus(); - if (status == Friend.STATUS_OFFLINE && c.isHandshakeReceived()) { - // fix it... - boolean handshakeCompletedFully = c.isFileListReceived(); - if (!handshakeCompletedFully) { - Debug.out(""getConnectedFriends, existing connection found, settings to handshaking: "" + remoteFriend.getNick()); - remoteFriend.setStatus(Friend.STATUS_HANDSHAKING); - } else { - Debug.out(""getConnectedFriends, existing connection found, settings to connected: "" + remoteFriend.getNick()); - remoteFriend.setConnectionId(c.hashCode()); - remoteFriend.setStatus(Friend.STATUS_ONLINE); - } - } - } - - Map l = new HashMap(connections.size()); - /* - * we don't show me in friends list anymore - */ - // l.put(me.getConnectionIds().get(0), me); - Friend[] friends = friendManager.getFriends(); - for (Friend friend : friends) { - if (friend.getStatus() == Friend.STATUS_ONLINE) { - // System.out.println(""online: "" + friend.getNick()); - l.put(friend.getConnectionId(), friend); - } - } - - return l; - } - - public int getSearchDelayForInfohash(Friend destination, byte[] infohash) { - if (destination.isCanSeeFileList()) { - return 0; - } else { - int searchDelay = responseDelayRandomnesManager.getDeterministicNextInt(infohash, mMIN_RESPONSE_DELAY, mMAX_RESPONSE_DELAY); - int latencyDelay = getLatencyDelayForInfohash(destination, infohash); - return searchDelay + latencyDelay; - } - } - - public int getLatencyDelayForInfohash(Friend destination, byte[] infohash) { - if (destination.isCanSeeFileList()) { - return 0; - } else { - return responseDelayRandomnesManager.getDeterministicNextInt(infohash, mMIN_DELAY_LINK_LATENCY, mMAX_DELAY_LINK_LATENCY); - } - } - - - public List getDisconnectedFriends() { - List l = new ArrayList(); - Friend[] friends = friendManager.getFriends(); - for (Friend friend : friends) { - if (friend.getStatus() != Friend.STATUS_ONLINE) { - l.add(friend); - } - } - return l; - } - - public FileListManager getFilelistManager() { - return filelistManager; - } - - public List getFriendConnections() { - return new ArrayList(connections.values()); - } - - // private int parallelConnectCount(InetAddress remoteIP, byte[] - // remotePubKey) { - // int count = 0; - // for (FriendConnection overlayConnection : connections.values()) { - // if (overlayConnection.getRemoteIp().equals(remoteIP) - // && Arrays.equals(overlayConnection.getRemotePublicKey(), - // remotePubKey)) { - // count++; - // } - // } - // - // return count; - // } - - public long getLastConnectionCheckRun() { - return lastConnectionCheckRun; - } - - public PublicKey getOwnPublicKey() { - return ownPublicKey; - } - - public QueueManager getQueueManager() { - return queueManager; - } - - public SearchManager getSearchManager() { - return searchManager; - } - - public double getTransportDownloadKBps() { - long totalDownloadSpeed = 0; - - LinkedList conns = new LinkedList(); - conns.addAll(connections.values()); - - for (FriendConnection fc : conns) { - final Map ot = fc.getOverlayTransports(); - - for (OverlayTransport o : ot.values()) { - totalDownloadSpeed += o.getDownloadRate(); - } - } - - return totalDownloadSpeed / 1024.0; - } - - public long getTransportSendRate(boolean includeLan) { - long totalUploadSpeed = 0; - - LinkedList conns = new LinkedList(); - conns.addAll(connections.values()); - - for (FriendConnection fc : conns) { - final Map ot = fc.getOverlayTransports(); - - for (OverlayTransport o : ot.values()) { - if (!includeLan && o.isLANLocal()) { - // not including lan local peers - } else { - totalUploadSpeed += o.getUploadRate(); - } - } - } - - return totalUploadSpeed; - } - - public boolean isConnectionAllowed(InetAddress remoteIP, byte[] remotePubKey) { - Friend friend = friendManager.getFriend(remotePubKey); - if (stopped) { - Log.log(""connection denied: (f2f transfers disabled)"", logToStdOut); - return false; - } - // check if we should allow this public key to connect - if (Arrays.equals(remotePubKey, ownPublicKey.getEncoded()) && remoteIP.equals(myInstance.getExternalAddress())) { - Log.log(LogEvent.LT_INFORMATION, ""connection from self not allowed (if same ip)"", logToStdOut); - return false; - } else if (friend == null) { - Log.log(LogEvent.LT_WARNING, "" access denied (not friend): "" + remoteIP, logToStdOut); - return false; - } else if (friend.isBlocked()) { - Log.log(LogEvent.LT_WARNING, "" access denied (friend blocked): "" + remoteIP, logToStdOut); - return false; - } else if (friend.getFriendBannedUntil() > System.currentTimeMillis()) { - double minutesLeft = friend.getFriendBannedUntil() - System.currentTimeMillis() / (60 * 1000.0); - friend.updateConnectionLog(true, ""incoming connection denied, friend blocked for "" + minutesLeft + "" more minutes because of: "" + friend.getBannedReason()); - Log.log(LogEvent.LT_WARNING, "" access denied (friend blocked for "" + minutesLeft + "" more minutes): "" + remoteIP, logToStdOut); - return false; - } - - for (FriendConnection c : connections.values()) { - if (c.getRemoteFriend().equals(friend)) { - Log.log(LogEvent.LT_WARNING, "" access denied (friend already connected): "" + remoteIP, logToStdOut); - return false; - } - } - Log.log(LogEvent.LT_INFORMATION, ""friend connection ok: "" + remoteIP + "" :: "" + friend, logToStdOut); - return true; - } - - /** - * make sure to synchronize before calling this function - */ - private void notifyConnectionListeners(Friend f, boolean connected) { - lock.lock(); - try { - for (FriendConnectListener cb : friendConnectListeners) { - if (connected) { - cb.friendConnected(f); - } else { - cb.friendDisconnected(f); - } - } - } finally { - lock.unlock(); - } - } - - private boolean registerConnection(FriendConnection connection) { - lock.lock(); - try { - if (isConnectionAllowed(connection.getRemoteIp(), connection.getRemotePublicKey())) { - connections.put(connection.hashCode(), connection); - /* - * don't mark remote friend as connected until after the - * oneswarm handshake message is received - */ - // connection.getRemoteFriend().connected(connection.hashCode()); - Log.log(""registered connection: "" + connection, logToStdOut); - return true; - } else { - return false; - } - } finally { - lock.unlock(); - } - } - - public void registerForConnectNotifications(FriendConnectListener callback) { - lock.lock(); - try { - friendConnectListeners.add(callback); - } finally { - lock.unlock(); - } - } - - public void restartAllConnections() { - stopped = false; - } - - public void sendChatMessage(int connectionId, String inPlaintextMessage) { - FriendConnection conn = connections.get(connectionId); - conn.sendChat(inPlaintextMessage); - } - - void sendDirectedSearch(FriendConnection target, OSF2FHashSearch search) { - Log.log(""sending search to "" + target, logToStdOut); - target.sendSearch(search, true); - } - - public boolean sendFileListRequest(int connectionId, long maxCacheAge, PluginCallback callback) { - - // just check if the request is for the local list - if (connectionId == OWN_CONNECTION_ID_MAGIC_NUMBER) { - callback.requestCompleted(filelistManager.getOwnFileList()); - } - - FriendConnection conn = connections.get(connectionId); - - if (conn != null) { - - FileList oldList = filelistManager.getFriendsList(conn.getRemoteFriend()); - if (oldList != null && (System.currentTimeMillis() - oldList.getCreated()) < maxCacheAge) { - callback.requestCompleted(oldList); - } - - Log.log(""sending filelist request to "" + conn); - conn.sendFileListRequest(OSF2FMessage.FILE_LIST_TYPE_COMPLETE, callback); - return true; - } else { - System.err.println(""tried to get filelist for unknown connection id (friend just went offline?)!, stack trace is:""); - new RuntimeException().printStackTrace(); - } - return false; - } - - // public void startDownload(byte type, byte[] metainfo, - // boolean createIfNotExist) { - // if (type == OSF2FMessage.METAINFO_TYPE_BITTORRENT) { - // - - public boolean sendMetaInfoRequest(int connectionId, int channelId, byte[] infohash, int lengthHint, PluginCallback callback) { - FriendConnection conn = connections.get(connectionId); - Log.log(""sending metainfo request to "" + conn); - if (conn != null) { - conn.sendMetaInfoRequest(OSF2FMessage.METAINFO_TYPE_BITTORRENT, channelId, infohash, lengthHint, callback); - return true; - } - return false; - - } - - void sendSearchOrCancel(OSF2FSearch search, boolean skipQueue, boolean forceSend) { - Log.log(""sending search/cancel to "" + connections.size(), logToStdOut); - int numSent = 0; - for (FriendConnection conn : connections.values()) { - - boolean shouldSend = true; - if (!forceSend) { - shouldSend = shouldForwardSearch(search, conn); - } - if (shouldSend) { - conn.sendSearch(search.clone(), skipQueue); - numSent++; - } - if (search instanceof OSF2FHashSearch) { - OSF2FHashSearch hs = (OSF2FHashSearch) search; - searchTimingsLogger.log(System.currentTimeMillis() + "", send_search, "" + conn.getRemoteFriend().getNick() + "", "" + hs.getSearchID() + "", "" + hs.getInfohashhash()); - } - } - /* - * for searches sent by us, if we didn't send it to anyone try again but - * without the randomness linitng who we are sending to - */ - if (numSent == 0 && !forceSend) { - sendSearchOrCancel(search, skipQueue, true); - } - } - - /** - * to protect against colluding friends we are only forwarding searches with - * 95% probability - * - * if forcesend = true the search will be forwarded anyway even if the - * randomness says that friend shouldn't be forwarded - */ - private boolean shouldForwardSearch(OSF2FSearch search, FriendConnection conn) { - boolean shouldSend = true; - if (search instanceof OSF2FHashSearch) { - shouldSend = shouldForwardSearch(((OSF2FHashSearch) search).getInfohashhash(), conn); - } else if (search instanceof OSF2FSearchCancel) { - long infohash = searchManager.getInfoHashHashFromSearchId(search.getSearchID()); - if (infohash != -1) { - shouldSend = shouldForwardSearch(infohash, conn); - } else { - shouldSend = false; - } - } - return shouldSend; - } - - private boolean shouldForwardSearch(long infohashhash, FriendConnection conn) { - if (conn.getRemoteFriend().isCanSeeFileList()) { - return true; - } - byte[] infohashbytes = RandomnessManager.getBytes(infohashhash); - byte[] friendHash = RandomnessManager.getBytes(conn.getRemotePublicKeyHash()); - byte[] all = new byte[infohashbytes.length + friendHash.length]; - System.arraycopy(infohashbytes, 0, all, 0, infohashbytes.length); - System.arraycopy(friendHash, 0, all, infohashbytes.length, friendHash.length); - - int randomVal = randomnessManager.getDeterministicRandomInt(all); - if (randomVal < 0) { - randomVal = -randomVal; - } - if (randomVal < Integer.MAX_VALUE * mForwardSearchProbability) { - return true; - } else { - return false; - } - } - - public void triggerFileListUpdates() { - List conns = new LinkedList(); - lock.lock(); - try { - conns.addAll(connections.values()); - } finally { - lock.unlock(); - } - for (FriendConnection conn : connections.values()) { - conn.triggerFileListSend(); - } - } - - private class ConnectionChecker extends TimerTask { - - @Override - public void run() { - - try { - // first, check if we have any overlays that are timed out - for (FriendConnection connection : connections.values()) { - connection.clearTimedOutForwards(); - connection.clearTimedOutTransports(); - connection.clearTimedOutSearchRecords(); - connection.clearOldMetainfoRequests(); - } - } catch (Throwable t) { - Debug.out(""F2F Connection Checker: got error when clearing transports/forwards"", t); - } - try { - // then, check if we need to send any keepalives - for (FriendConnection connection : connections.values()) { - connection.doKeepAliveCheck(); - } - } catch (Throwable t) { - Debug.out(""F2F Connection Checker: got error when sending keep alives"", t); - } - - try { - // check if we have any timed out connections - List timedOut = new ArrayList(); - for (FriendConnection connection : connections.values()) { - if (connection.isTimedOut()) { - timedOut.add(connection); - } - } - // and close them - for (FriendConnection friendConnection : timedOut) { - friendConnection.close(); - } - } catch (Throwable t) { - Debug.out(""F2F Connection Checker: got error when clearing friend connections"", t); - } - - try { - // then, recycle the search IDs - searchManager.clearTimedOutSearches(); - } catch (Throwable t) { - Debug.out(""F2F Connection Checker: got error when clearing timed out searches"", t); - } - lastConnectionCheckRun = System.currentTimeMillis(); - } - } - - class FriendConnectionListener { - public boolean connectSuccess(FriendConnection friendConnection) { - if (!registerConnection(friendConnection)) { - Log.log(""Unable to register connection, "" + ""connect count to high, closing connection"", logToStdOut); - friendConnection.close(); - return false; - } - return true; - } - - public void disconnected(FriendConnection friendConnection) { - if (friendConnection.isFileListReceived()) { - notifyConnectionListeners(friendConnection.getRemoteFriend(), false); - } - deregisterConnection(friendConnection); - } - - public void gotSearchCancel(FriendConnection friendConnection, OSF2FSearchCancel msg) { - searchManager.handleIncomingSearchCancel(friendConnection, msg); - } - - public void gotSearchMessage(FriendConnection friendConnection, OSF2FSearch msg) { - if (msg instanceof OSF2FHashSearch) { - OSF2FHashSearch hs = (OSF2FHashSearch) msg; - searchTimingsLogger.log(System.currentTimeMillis() + "", search, "" + friendConnection.getRemoteFriend().getNick() + "", "" + hs.getSearchID() + "", "" + hs.getInfohashhash() + "", "" + friendConnection.getRemoteIp().getHostAddress()); - } - searchManager.handleIncomingSearch(friendConnection, msg); - } - - public void gotSearchResponse(FriendConnection friendConnection, OSF2FSearchResp msg) { - if (msg instanceof OSF2FHashSearchResp) { - OSF2FHashSearchResp hsr = (OSF2FHashSearchResp) msg; - searchTimingsLogger.log(System.currentTimeMillis() + "", response, "" + friendConnection.getRemoteFriend().getNick() + "", "" + hsr.getSearchID() + "", "" + hsr.getChannelID() + "", "" + friendConnection.getRemoteIp().getHostAddress() + "", "" + hsr.getPathID()); - } - searchManager.handleIncomingSearchResponse(friendConnection, msg); - } - - @SuppressWarnings(""unchecked"") - public void handshakeCompletedFully(final FriendConnection friendConnection) { - - notifyConnectionListeners(friendConnection.getRemoteFriend(), true); - - /* - * check if we have any running downloads that this friend has - */ - Log.log(""New friend connected, checking if friend has anything we want"", logToStdOut); - List runningDownloadHashes = new LinkedList(); - List dms = AzureusCoreImpl.getSingleton().getGlobalManager().getDownloadManagers(); - for (DownloadManager dm : dms) { - if (dm.getState() == DownloadManager.STATE_DOWNLOADING) { - try { - TOTorrent torrent = dm.getTorrent(); - if (torrent != null) { - runningDownloadHashes.add(torrent.getHash()); - } - } catch (TOTorrentException e) { - e.printStackTrace(); - } - } - } - Log.log(""found "" + runningDownloadHashes.size() + "" running downloads"", logToStdOut); - FileList remoteFileList = filelistManager.getFriendsList(friendConnection.getRemoteFriend()); - for (byte[] hash : runningDownloadHashes) { - if (remoteFileList.contains(hash)) { - Log.log(""sending search for '"" + Base32.encode(hash) + ""' to "" + friendConnection.getRemoteFriend(), logToStdOut); - searchManager.sendDirectedHashSearch(friendConnection, hash); - } - } - - /** - * Check if we need to send any pending chat messages to this user. (5/sec) - */ - Thread queryThread = new Thread(""Queued chat SQL query for: "" + friendConnection.getRemoteFriend().getNick()) { - @Override - public void run() { - - try { - Thread.sleep(3*1000); - } catch( InterruptedException e ) {} - - String base64Key = new String(Base64.encode(friendConnection.getRemotePublicKey())); - ChatDAO dao = ChatDAO.get(); - List out = dao.getQueuedMessagesForUser(base64Key); - for( Chat c : out ) { - if( friendConnection.isTimedOut() || friendConnection.isClosing() ) { - return; - } - - friendConnection.sendChat(c.getMessage() + "" (sent "" + StringTools.formatDateAppleLike(new Date(c.getTimestamp()), true) + "")""); - dao.markSent(c.getUID()); - - try { - Thread.sleep(200); - } catch( InterruptedException e ) {} - } - } - }; - queryThread.setDaemon(true); - queryThread.start(); - } - } + /** + * make sure to not call any az functions when holding this lock + */ + public static BigFatLock lock = BigFatLock.getInstance(false); + + // private Friend me; + public static boolean logToStdOut = false; + + private int mMIN_DELAY_LINK_LATENCY = COConfigurationManager + .getIntParameter(""f2f_search_emulate_hops_min"") + * COConfigurationManager.getIntParameter(""f2f_overlay_emulate_link_latency_max""); + private int mMAX_DELAY_LINK_LATENCY = COConfigurationManager + .getIntParameter(""f2f_search_emulate_hops_max"") + * COConfigurationManager.getIntParameter(""f2f_overlay_emulate_link_latency_max""); + private int mMIN_RESPONSE_DELAY = COConfigurationManager + .getIntParameter(""f2f_search_emulate_hops_min"") + * COConfigurationManager.getIntParameter(""f2f_search_forward_delay""); + private int mMAX_RESPONSE_DELAY = COConfigurationManager + .getIntParameter(""f2f_search_emulate_hops_max"") + * COConfigurationManager.getIntParameter(""f2f_search_forward_delay""); + + private double mForwardSearchProbability = COConfigurationManager + .getFloatParameter(""f2f_forward_search_probability""); + + // this is just a way to treat requests for the local file list a bit + // differently + public final static int OWN_CONNECTION_ID_MAGIC_NUMBER = 0; + + private final static String RESPONSE_DELAY_SEED_SETTING_KEY = ""response_delay_seed""; + + private static final int TIMEOUT_CHECK_PERIOD = 5 * 1000; + private final ConcurrentHashMap connections; + private final FileListManager filelistManager; + private final LinkedList friendConnectListeners = new LinkedList(); + + private final FriendManager friendManager; + private long lastConnectionCheckRun = System.currentTimeMillis(); + + private final AZInstance myInstance; + private final PublicKey ownPublicKey; + private final QueueManager queueManager = new QueueManager(); + private final RandomnessManager randomnessManager; + private final RandomnessManager responseDelayRandomnesManager; + private final SearchManager searchManager; + + public RotatingLogger searchTimingsLogger = new RotatingLogger(""search_timing""); + + private final GlobalManagerStats stats; + + private boolean stopped = false; + private final Timer t = new Timer(""FriendConnectionInitialChecker"", true); + + public OverlayManager(FriendManager _friendManager, PublicKey _ownPublicKey, + FileListManager _fileListManager, GlobalManagerStats _stats) { + stats = _stats; + myInstance = AzureusCoreImpl.getSingleton().getInstanceManager().getMyInstance(); + + this.randomnessManager = new RandomnessManager(); + this.friendManager = _friendManager; + this.filelistManager = _fileListManager; + this.ownPublicKey = _ownPublicKey; + this.connections = new ConcurrentHashMap(); + this.searchManager = new SearchManager(this, filelistManager, randomnessManager, stats); + + byte[] seedBytes = COConfigurationManager.getByteParameter(RESPONSE_DELAY_SEED_SETTING_KEY); + if (seedBytes != null) { + responseDelayRandomnesManager = new RandomnessManager(seedBytes); + } else { + responseDelayRandomnesManager = new RandomnessManager(); + COConfigurationManager.setParameter(RESPONSE_DELAY_SEED_SETTING_KEY, + randomnessManager.getSecretBytes()); + } + + COConfigurationManager.addAndFireParameterListeners(new String[] { + ""f2f_overlay_emulate_link_latency_max"", ""f2f_search_emulate_hops_min"", + ""f2f_search_emulate_hops_max"", ""f2f_search_forward_delay"", + ""f2f_forward_search_probability"" }, new ParameterListener() { + public void parameterChanged(String parameterName) { + mMIN_DELAY_LINK_LATENCY = COConfigurationManager + .getIntParameter(""f2f_search_emulate_hops_min"") + * COConfigurationManager + .getIntParameter(""f2f_overlay_emulate_link_latency_max""); + mMAX_DELAY_LINK_LATENCY = COConfigurationManager + .getIntParameter(""f2f_search_emulate_hops_max"") + * COConfigurationManager + .getIntParameter(""f2f_overlay_emulate_link_latency_max""); + mMIN_RESPONSE_DELAY = COConfigurationManager + .getIntParameter(""f2f_search_emulate_hops_min"") + * COConfigurationManager.getIntParameter(""f2f_search_forward_delay""); + mMAX_RESPONSE_DELAY = COConfigurationManager + .getIntParameter(""f2f_search_emulate_hops_max"") + * COConfigurationManager.getIntParameter(""f2f_search_forward_delay""); + mForwardSearchProbability = COConfigurationManager + .getFloatParameter(""f2f_forward_search_probability""); + + if (mForwardSearchProbability <= 0) { + COConfigurationManager.setParameter(""f2f_forward_search_probability"", 0.5f); + mForwardSearchProbability = 0.5; + } + System.err.println(""f2f_search_fwd_p: "" + mForwardSearchProbability); + } + }); + + OSF2FMessageFactory.init(); + + Timer timeoutTimer = new Timer(""OS Overlay Timeout checker"", true); + timeoutTimer.schedule(new ConnectionChecker(), 0, TIMEOUT_CHECK_PERIOD); + + } + + public void closeAllConnections() { + for (FriendConnection c : connections.values()) { + c.close(); + } + + stopped = true; + } + + public boolean createIncomingConnection(byte[] publicKey, NetworkConnection netConn) { + + if (isConnectionAllowed(netConn.getEndpoint().getNotionalAddress().getAddress(), publicKey)) { + Friend friend = friendManager.getFriend(publicKey); + new FriendConnection(stats, queueManager, netConn, friend, filelistManager, + new FriendConnectionListener()); + + return true; + } + return false; + } + + public boolean createOutgoingConnection(ConnectionEndpoint remoteFriendAddr, Friend friend) { + if (isConnectionAllowed(remoteFriendAddr.getNotionalAddress().getAddress(), + friend.getPublicKey())) { + final FriendConnection fc = new FriendConnection(stats, queueManager, remoteFriendAddr, + friend, filelistManager, new FriendConnectionListener()); + /* + * create a check for this connection to verify that we actually get + * connected within a reasonable time frame + */ + t.schedule(new TimerTask() { + @Override + public void run() { + if (fc.isTimedOut()) { + fc.close(); + } + } + }, FriendConnection.INITIAL_HANDSHAKE_TIMEOUT + 10 * 1000); + + return true; + } + return false; + } + + private boolean deregisterConnection(FriendConnection connection) { + lock.lock(); + try { + Log.log(""deregistered connection: "" + connection.toString() + "" "" + + connections.containsKey(connection.hashCode()) + "" "", logToStdOut); + boolean res = null != connections.remove(connection.hashCode()); + Friend remoteFriend = connection.getRemoteFriend(); + + /* + * check if there are any active connections to the friend, if not, + * mark as disconnected + * + * this check is needed if there are 2 concurrent connections to the + * same friend , and one is denied to register because of the other + * one already connected + */ + + FriendConnection connectedConn = null; + for (FriendConnection c : connections.values()) { + if (c.getRemoteFriend().equals(remoteFriend)) { + connectedConn = c; + } + } + /* + * if the connection id != null, verify that the friend actually + * think it is connected to the right connection id + */ + if (connectedConn != null && connectedConn.isHandshakeReceived()) { + int friendConnId = remoteFriend.getConnectionId(); + if (connectedConn.hashCode() != friendConnId) { + // fix it... + boolean fileListReceived = connectedConn.isFileListReceived(); + if (!fileListReceived) { + Log.log(""connection closed, existing connection found, set to handshaking: "" + + remoteFriend.getNick(), logToStdOut); + remoteFriend.setStatus(Friend.STATUS_HANDSHAKING); + remoteFriend.setConnectionId(Friend.NOT_CONNECTED_CONNECTION_ID); + } else { + Log.log(""connection closed, existing connection found, set to connected: "" + + remoteFriend.getNick(), logToStdOut); + remoteFriend.setConnectionId(connectedConn.hashCode()); + remoteFriend.setStatus(Friend.STATUS_ONLINE); + } + } + } else { + // ok, no existing connections, mark as disconnected. + remoteFriend.disconnected(connection.hashCode()); + } + + return res; + } finally { + lock.unlock(); + } + } + + public void disconnectFriend(Friend f) { + for (FriendConnection conn : connections.values()) { + if (conn.getRemoteFriend().equals(f)) { + conn.close(); + } + } + } + + void forwardSearchOrCancel(FriendConnection ignoreConn, OSF2FSearch msg) { + for (FriendConnection conn : connections.values()) { + if (ignoreConn.hashCode() == conn.hashCode()) { + Log.log(""not forwarding search/cancel to: "" + conn + "" (source friend)"", + logToStdOut); + continue; + } + Log.log(""forwarding search/cancel to: "" + conn, logToStdOut); + if (shouldForwardSearch(msg, ignoreConn)) { + conn.sendSearch(msg.clone(), false); + } + } + } + + public int getConnectCount() { + return connections.size(); + } + + public Map getConnectedFriends() { + // sanity checks + for (int connectionId : connections.keySet()) { + FriendConnection c = connections.get(connectionId); + // check status just to make sure + final Friend remoteFriend = c.getRemoteFriend(); + int status = remoteFriend.getStatus(); + if (status == Friend.STATUS_OFFLINE && c.isHandshakeReceived()) { + // fix it... + boolean handshakeCompletedFully = c.isFileListReceived(); + if (!handshakeCompletedFully) { + Debug.out(""getConnectedFriends, existing connection found, settings to handshaking: "" + + remoteFriend.getNick()); + remoteFriend.setStatus(Friend.STATUS_HANDSHAKING); + } else { + Debug.out(""getConnectedFriends, existing connection found, settings to connected: "" + + remoteFriend.getNick()); + remoteFriend.setConnectionId(c.hashCode()); + remoteFriend.setStatus(Friend.STATUS_ONLINE); + } + } + } + + Map l = new HashMap(connections.size()); + /* + * we don't show me in friends list anymore + */ + // l.put(me.getConnectionIds().get(0), me); + Friend[] friends = friendManager.getFriends(); + for (Friend friend : friends) { + if (friend.getStatus() == Friend.STATUS_ONLINE) { + // System.out.println(""online: "" + friend.getNick()); + l.put(friend.getConnectionId(), friend); + } + } + + return l; + } + + public int getSearchDelayForInfohash(Friend destination, byte[] infohash) { + if (destination.isCanSeeFileList()) { + return 0; + } else { + int searchDelay = responseDelayRandomnesManager.getDeterministicNextInt(infohash, + mMIN_RESPONSE_DELAY, mMAX_RESPONSE_DELAY); + int latencyDelay = getLatencyDelayForInfohash(destination, infohash); + return searchDelay + latencyDelay; + } + } + + public int getLatencyDelayForInfohash(Friend destination, byte[] infohash) { + if (destination.isCanSeeFileList()) { + return 0; + } else { + return responseDelayRandomnesManager.getDeterministicNextInt(infohash, + mMIN_DELAY_LINK_LATENCY, mMAX_DELAY_LINK_LATENCY); + } + } + + public List getDisconnectedFriends() { + List l = new ArrayList(); + Friend[] friends = friendManager.getFriends(); + for (Friend friend : friends) { + if (friend.getStatus() != Friend.STATUS_ONLINE) { + l.add(friend); + } + } + return l; + } + + public FileListManager getFilelistManager() { + return filelistManager; + } + + public List getFriendConnections() { + return new ArrayList(connections.values()); + } + + // private int parallelConnectCount(InetAddress remoteIP, byte[] + // remotePubKey) { + // int count = 0; + // for (FriendConnection overlayConnection : connections.values()) { + // if (overlayConnection.getRemoteIp().equals(remoteIP) + // && Arrays.equals(overlayConnection.getRemotePublicKey(), + // remotePubKey)) { + // count++; + // } + // } + // + // return count; + // } + + public long getLastConnectionCheckRun() { + return lastConnectionCheckRun; + } + + public PublicKey getOwnPublicKey() { + return ownPublicKey; + } + + public QueueManager getQueueManager() { + return queueManager; + } + + public SearchManager getSearchManager() { + return searchManager; + } + + public double getTransportDownloadKBps() { + long totalDownloadSpeed = 0; + + LinkedList conns = new LinkedList(); + conns.addAll(connections.values()); + + for (FriendConnection fc : conns) { + final Map ot = fc.getOverlayTransports(); + + for (OverlayEndpoint o : ot.values()) { + totalDownloadSpeed += o.getDownloadRate(); + } + } + + return totalDownloadSpeed / 1024.0; + } + + public long getTransportSendRate(boolean includeLan) { + long totalUploadSpeed = 0; + + LinkedList conns = new LinkedList(); + conns.addAll(connections.values()); + + for (FriendConnection fc : conns) { + final Map ot = fc.getOverlayTransports(); + + for (OverlayEndpoint o : ot.values()) { + if (!includeLan && o.isLANLocal()) { + // not including lan local peers + } else { + totalUploadSpeed += o.getUploadRate(); + } + } + } + + return totalUploadSpeed; + } + + public boolean isConnectionAllowed(InetAddress remoteIP, byte[] remotePubKey) { + Friend friend = friendManager.getFriend(remotePubKey); + if (stopped) { + Log.log(""connection denied: (f2f transfers disabled)"", logToStdOut); + return false; + } + // check if we should allow this public key to connect + if (Arrays.equals(remotePubKey, ownPublicKey.getEncoded()) + && remoteIP.equals(myInstance.getExternalAddress())) { + Log.log(LogEvent.LT_INFORMATION, ""connection from self not allowed (if same ip)"", + logToStdOut); + return false; + } else if (friend == null) { + Log.log(LogEvent.LT_WARNING, "" access denied (not friend): "" + remoteIP, logToStdOut); + return false; + } else if (friend.isBlocked()) { + Log.log(LogEvent.LT_WARNING, "" access denied (friend blocked): "" + remoteIP, + logToStdOut); + return false; + } else if (friend.getFriendBannedUntil() > System.currentTimeMillis()) { + double minutesLeft = friend.getFriendBannedUntil() - System.currentTimeMillis() + / (60 * 1000.0); + friend.updateConnectionLog(true, ""incoming connection denied, friend blocked for "" + + minutesLeft + "" more minutes because of: "" + friend.getBannedReason()); + Log.log(LogEvent.LT_WARNING, "" access denied (friend blocked for "" + minutesLeft + + "" more minutes): "" + remoteIP, logToStdOut); + return false; + } + + for (FriendConnection c : connections.values()) { + if (c.getRemoteFriend().equals(friend)) { + Log.log(LogEvent.LT_WARNING, "" access denied (friend already connected): "" + + remoteIP, logToStdOut); + return false; + } + } + Log.log(LogEvent.LT_INFORMATION, ""friend connection ok: "" + remoteIP + "" :: "" + friend, + logToStdOut); + return true; + } + + /** + * make sure to synchronize before calling this function + */ + private void notifyConnectionListeners(Friend f, boolean connected) { + lock.lock(); + try { + for (FriendConnectListener cb : friendConnectListeners) { + if (connected) { + cb.friendConnected(f); + } else { + cb.friendDisconnected(f); + } + } + } finally { + lock.unlock(); + } + } + + private boolean registerConnection(FriendConnection connection) { + lock.lock(); + try { + if (isConnectionAllowed(connection.getRemoteIp(), connection.getRemotePublicKey())) { + connections.put(connection.hashCode(), connection); + /* + * don't mark remote friend as connected until after the + * oneswarm handshake message is received + */ + // connection.getRemoteFriend().connected(connection.hashCode()); + Log.log(""registered connection: "" + connection, logToStdOut); + return true; + } else { + return false; + } + } finally { + lock.unlock(); + } + } + + public void registerForConnectNotifications(FriendConnectListener callback) { + lock.lock(); + try { + friendConnectListeners.add(callback); + } finally { + lock.unlock(); + } + } + + public void restartAllConnections() { + stopped = false; + } + + public void sendChatMessage(int connectionId, String inPlaintextMessage) { + FriendConnection conn = connections.get(connectionId); + conn.sendChat(inPlaintextMessage); + } + + void sendDirectedSearch(FriendConnection target, OSF2FHashSearch search) { + Log.log(""sending search to "" + target, logToStdOut); + target.sendSearch(search, true); + } + + public boolean sendFileListRequest(int connectionId, long maxCacheAge, + PluginCallback callback) { + + // just check if the request is for the local list + if (connectionId == OWN_CONNECTION_ID_MAGIC_NUMBER) { + callback.requestCompleted(filelistManager.getOwnFileList()); + } + + FriendConnection conn = connections.get(connectionId); + + if (conn != null) { + + FileList oldList = filelistManager.getFriendsList(conn.getRemoteFriend()); + if (oldList != null + && (System.currentTimeMillis() - oldList.getCreated()) < maxCacheAge) { + callback.requestCompleted(oldList); + } + + Log.log(""sending filelist request to "" + conn); + conn.sendFileListRequest(OSF2FMessage.FILE_LIST_TYPE_COMPLETE, callback); + return true; + } else { + System.err + .println(""tried to get filelist for unknown connection id (friend just went offline?)!, stack trace is:""); + new RuntimeException().printStackTrace(); + } + return false; + } + + // public void startDownload(byte type, byte[] metainfo, + // boolean createIfNotExist) { + // if (type == OSF2FMessage.METAINFO_TYPE_BITTORRENT) { + // + + public boolean sendMetaInfoRequest(int connectionId, int channelId, byte[] infohash, + int lengthHint, PluginCallback callback) { + FriendConnection conn = connections.get(connectionId); + Log.log(""sending metainfo request to "" + conn); + if (conn != null) { + conn.sendMetaInfoRequest(OSF2FMessage.METAINFO_TYPE_BITTORRENT, channelId, infohash, + lengthHint, callback); + return true; + } + return false; + + } + + void sendSearchOrCancel(OSF2FSearch search, boolean skipQueue, boolean forceSend) { + Log.log(""sending search/cancel to "" + connections.size(), logToStdOut); + int numSent = 0; + for (FriendConnection conn : connections.values()) { + + boolean shouldSend = true; + if (!forceSend) { + shouldSend = shouldForwardSearch(search, conn); + } + if (shouldSend) { + conn.sendSearch(search.clone(), skipQueue); + numSent++; + } + if (search instanceof OSF2FHashSearch) { + OSF2FHashSearch hs = (OSF2FHashSearch) search; + searchTimingsLogger.log(System.currentTimeMillis() + "", send_search, "" + + conn.getRemoteFriend().getNick() + "", "" + hs.getSearchID() + "", "" + + hs.getInfohashhash()); + } + } + /* + * for searches sent by us, if we didn't send it to anyone try again but + * without the randomness linitng who we are sending to + */ + if (numSent == 0 && !forceSend) { + sendSearchOrCancel(search, skipQueue, true); + } + } + + /** + * to protect against colluding friends we are only forwarding searches with + * 95% probability + * + * if forcesend = true the search will be forwarded anyway even if the + * randomness says that friend shouldn't be forwarded + */ + private boolean shouldForwardSearch(OSF2FSearch search, FriendConnection conn) { + boolean shouldSend = true; + if (search instanceof OSF2FHashSearch) { + shouldSend = shouldForwardSearch(((OSF2FHashSearch) search).getInfohashhash(), conn); + } else if (search instanceof OSF2FSearchCancel) { + long infohash = searchManager.getInfoHashHashFromSearchId(search.getSearchID()); + if (infohash != -1) { + shouldSend = shouldForwardSearch(infohash, conn); + } else { + shouldSend = false; + } + } + return shouldSend; + } + + private boolean shouldForwardSearch(long infohashhash, FriendConnection conn) { + if (conn.getRemoteFriend().isCanSeeFileList()) { + return true; + } + byte[] infohashbytes = RandomnessManager.getBytes(infohashhash); + byte[] friendHash = RandomnessManager.getBytes(conn.getRemotePublicKeyHash()); + byte[] all = new byte[infohashbytes.length + friendHash.length]; + System.arraycopy(infohashbytes, 0, all, 0, infohashbytes.length); + System.arraycopy(friendHash, 0, all, infohashbytes.length, friendHash.length); + + int randomVal = randomnessManager.getDeterministicRandomInt(all); + if (randomVal < 0) { + randomVal = -randomVal; + } + if (randomVal < Integer.MAX_VALUE * mForwardSearchProbability) { + return true; + } else { + return false; + } + } + + public void triggerFileListUpdates() { + List conns = new LinkedList(); + lock.lock(); + try { + conns.addAll(connections.values()); + } finally { + lock.unlock(); + } + for (FriendConnection conn : connections.values()) { + conn.triggerFileListSend(); + } + } + + private class ConnectionChecker extends TimerTask { + + @Override + public void run() { + + try { + // first, check if we have any overlays that are timed out + for (FriendConnection connection : connections.values()) { + connection.clearTimedOutForwards(); + connection.clearTimedOutTransports(); + connection.clearTimedOutSearchRecords(); + connection.clearOldMetainfoRequests(); + } + } catch (Throwable t) { + Debug.out(""F2F Connection Checker: got error when clearing transports/forwards"", t); + } + try { + // then, check if we need to send any keepalives + for (FriendConnection connection : connections.values()) { + connection.doKeepAliveCheck(); + } + } catch (Throwable t) { + Debug.out(""F2F Connection Checker: got error when sending keep alives"", t); + } + + try { + // check if we have any timed out connections + List timedOut = new ArrayList(); + for (FriendConnection connection : connections.values()) { + if (connection.isTimedOut()) { + timedOut.add(connection); + } + } + // and close them + for (FriendConnection friendConnection : timedOut) { + friendConnection.close(); + } + } catch (Throwable t) { + Debug.out(""F2F Connection Checker: got error when clearing friend connections"", t); + } + + try { + // then, recycle the search IDs + searchManager.clearTimedOutSearches(); + } catch (Throwable t) { + Debug.out(""F2F Connection Checker: got error when clearing timed out searches"", t); + } + lastConnectionCheckRun = System.currentTimeMillis(); + } + } + + class FriendConnectionListener { + public boolean connectSuccess(FriendConnection friendConnection) { + if (!registerConnection(friendConnection)) { + Log.log(""Unable to register connection, "" + + ""connect count to high, closing connection"", logToStdOut); + friendConnection.close(); + return false; + } + return true; + } + + public void disconnected(FriendConnection friendConnection) { + if (friendConnection.isFileListReceived()) { + notifyConnectionListeners(friendConnection.getRemoteFriend(), false); + } + deregisterConnection(friendConnection); + } + + public void gotSearchCancel(FriendConnection friendConnection, OSF2FSearchCancel msg) { + searchManager.handleIncomingSearchCancel(friendConnection, msg); + } + + public void gotSearchMessage(FriendConnection friendConnection, OSF2FSearch msg) { + if (msg instanceof OSF2FHashSearch) { + OSF2FHashSearch hs = (OSF2FHashSearch) msg; + searchTimingsLogger.log(System.currentTimeMillis() + "", search, "" + + friendConnection.getRemoteFriend().getNick() + "", "" + hs.getSearchID() + + "", "" + hs.getInfohashhash() + "", "" + + friendConnection.getRemoteIp().getHostAddress()); + } + searchManager.handleIncomingSearch(friendConnection, msg); + } + + public void gotSearchResponse(FriendConnection friendConnection, OSF2FSearchResp msg) { + if (msg instanceof OSF2FHashSearchResp) { + OSF2FHashSearchResp hsr = (OSF2FHashSearchResp) msg; + searchTimingsLogger.log(System.currentTimeMillis() + "", response, "" + + friendConnection.getRemoteFriend().getNick() + "", "" + hsr.getSearchID() + + "", "" + hsr.getChannelID() + "", "" + + friendConnection.getRemoteIp().getHostAddress() + "", "" + hsr.getPathID()); + } + searchManager.handleIncomingSearchResponse(friendConnection, msg); + } + + @SuppressWarnings(""unchecked"") + public void handshakeCompletedFully(final FriendConnection friendConnection) { + + notifyConnectionListeners(friendConnection.getRemoteFriend(), true); + + /* + * check if we have any running downloads that this friend has + */ + Log.log(""New friend connected, checking if friend has anything we want"", logToStdOut); + List runningDownloadHashes = new LinkedList(); + List dms = AzureusCoreImpl.getSingleton().getGlobalManager() + .getDownloadManagers(); + for (DownloadManager dm : dms) { + if (dm.getState() == DownloadManager.STATE_DOWNLOADING) { + try { + TOTorrent torrent = dm.getTorrent(); + if (torrent != null) { + runningDownloadHashes.add(torrent.getHash()); + } + } catch (TOTorrentException e) { + e.printStackTrace(); + } + } + } + Log.log(""found "" + runningDownloadHashes.size() + "" running downloads"", logToStdOut); + FileList remoteFileList = filelistManager.getFriendsList(friendConnection + .getRemoteFriend()); + for (byte[] hash : runningDownloadHashes) { + if (remoteFileList.contains(hash)) { + Log.log(""sending search for '"" + Base32.encode(hash) + ""' to "" + + friendConnection.getRemoteFriend(), logToStdOut); + searchManager.sendDirectedHashSearch(friendConnection, hash); + } + } + + /** + * Check if we need to send any pending chat messages to this user. + * (5/sec) + */ + Thread queryThread = new Thread(""Queued chat SQL query for: "" + + friendConnection.getRemoteFriend().getNick()) { + @Override + public void run() { + + try { + Thread.sleep(3 * 1000); + } catch (InterruptedException e) { + } + + String base64Key = new String(Base64.encode(friendConnection + .getRemotePublicKey())); + ChatDAO dao = ChatDAO.get(); + List out = dao.getQueuedMessagesForUser(base64Key); + for (Chat c : out) { + if (friendConnection.isTimedOut() || friendConnection.isClosing()) { + return; + } + + friendConnection.sendChat(c.getMessage() + "" (sent "" + + StringTools.formatDateAppleLike(new Date(c.getTimestamp()), true) + + "")""); + dao.markSent(c.getUID()); + + try { + Thread.sleep(200); + } catch (InterruptedException e) { + } + } + } + }; + queryThread.setDaemon(true); + queryThread.start(); + } + } } class RandomnessManager { - private byte[] secretBytes = new byte[20]; - - public RandomnessManager() { - SecureRandom random; - try { - random = SecureRandom.getInstance(""SHA1PRNG""); - random.nextBytes(secretBytes); - } catch (NoSuchAlgorithmException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - secretBytes = null; - } - } - - public RandomnessManager(byte[] secretBytes) { - this.secretBytes = secretBytes; - } - - /** - * returns a random int between 0 (inclusive) and n (exclusive) seeded by - * seedBytes - */ - - public int getDeterministicNextInt(byte[] seedBytes, int minValue, int maxValue) { - int randomInt = getDeterministicRandomInt(seedBytes); - if (randomInt < 0) { - randomInt = -randomInt; - } - return minValue + (randomInt % (maxValue - minValue)); - } - - public int getDeterministicNextInt(int seed, int minValue, int maxValue) { - byte[] seedBytes = getBytes(seed); - return getDeterministicNextInt(seedBytes, minValue, maxValue); - } - - public int getDeterministicNextInt(long seed, int minValue, int maxValue) { - byte[] seedBytes = getBytes(seed); - return getDeterministicNextInt(seedBytes, minValue, maxValue); - } - - public int getDeterministicRandomInt(byte[] seedBytes) { - if (secretBytes != null) { - byte[] sha1input = new byte[secretBytes.length + seedBytes.length]; - System.arraycopy(secretBytes, 0, sha1input, 0, secretBytes.length); - System.arraycopy(seedBytes, 0, sha1input, secretBytes.length, seedBytes.length); - MessageDigest md; - try { - md = MessageDigest.getInstance(""SHA-1""); - md.update(sha1input); - byte[] sha1 = md.digest(); - ByteArrayInputStream bis = new ByteArrayInputStream(sha1); - DataInputStream in = new DataInputStream(bis); - return in.readInt(); - } catch (NoSuchAlgorithmException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - throw new RuntimeException(""unable to generate deterministic random int""); - } - - /** - * Returns a random int seeded with the secret appended to the seed. For a - * given seed the returned value will always be the same for a given - * instance of the RandomnessManager - * - * @param seed - * @return - * @throws NoSuchAlgorithmException - * @throws IOException - */ - public int getDeterministicRandomInt(int seed) { - byte[] seedBytes = getBytes(seed); - return getDeterministicRandomInt(seedBytes); - } - - public int getDeterministicRandomInt(long seed) { - byte[] seedBytes = getBytes(seed); - return getDeterministicRandomInt(seedBytes); - } - - public byte[] getSecretBytes() { - return secretBytes; - } - - static byte[] getBytes(int val) { - byte[] b = new byte[4]; - b[3] = (byte) (val >>> 0); - b[2] = (byte) (val >>> 8); - b[1] = (byte) (val >>> 16); - b[0] = (byte) (val >>> 24); - return b; - } - - static byte[] getBytes(long val) { - byte[] b = new byte[8]; - b[7] = (byte) (val >>> 0); - b[6] = (byte) (val >>> 8); - b[5] = (byte) (val >>> 16); - b[4] = (byte) (val >>> 24); - b[3] = (byte) (val >>> 32); - b[2] = (byte) (val >>> 40); - b[1] = (byte) (val >>> 48); - b[0] = (byte) (val >>> 56); - return b; - } + private byte[] secretBytes = new byte[20]; + + public RandomnessManager() { + SecureRandom random; + try { + random = SecureRandom.getInstance(""SHA1PRNG""); + random.nextBytes(secretBytes); + } catch (NoSuchAlgorithmException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + secretBytes = null; + } + } + + public RandomnessManager(byte[] secretBytes) { + this.secretBytes = secretBytes; + } + + /** + * returns a random int between 0 (inclusive) and n (exclusive) seeded by + * seedBytes + */ + + public int getDeterministicNextInt(byte[] seedBytes, int minValue, int maxValue) { + int randomInt = getDeterministicRandomInt(seedBytes); + if (randomInt < 0) { + randomInt = -randomInt; + } + return minValue + (randomInt % (maxValue - minValue)); + } + + public int getDeterministicNextInt(int seed, int minValue, int maxValue) { + byte[] seedBytes = getBytes(seed); + return getDeterministicNextInt(seedBytes, minValue, maxValue); + } + + public int getDeterministicNextInt(long seed, int minValue, int maxValue) { + byte[] seedBytes = getBytes(seed); + return getDeterministicNextInt(seedBytes, minValue, maxValue); + } + + public int getDeterministicRandomInt(byte[] seedBytes) { + if (secretBytes != null) { + byte[] sha1input = new byte[secretBytes.length + seedBytes.length]; + System.arraycopy(secretBytes, 0, sha1input, 0, secretBytes.length); + System.arraycopy(seedBytes, 0, sha1input, secretBytes.length, seedBytes.length); + MessageDigest md; + try { + md = MessageDigest.getInstance(""SHA-1""); + md.update(sha1input); + byte[] sha1 = md.digest(); + ByteArrayInputStream bis = new ByteArrayInputStream(sha1); + DataInputStream in = new DataInputStream(bis); + return in.readInt(); + } catch (NoSuchAlgorithmException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + throw new RuntimeException(""unable to generate deterministic random int""); + } + + /** + * Returns a random int seeded with the secret appended to the seed. For a + * given seed the returned value will always be the same for a given + * instance of the RandomnessManager + * + * @param seed + * @return + * @throws NoSuchAlgorithmException + * @throws IOException + */ + public int getDeterministicRandomInt(int seed) { + byte[] seedBytes = getBytes(seed); + return getDeterministicRandomInt(seedBytes); + } + + public int getDeterministicRandomInt(long seed) { + byte[] seedBytes = getBytes(seed); + return getDeterministicRandomInt(seedBytes); + } + + public byte[] getSecretBytes() { + return secretBytes; + } + + static byte[] getBytes(int val) { + byte[] b = new byte[4]; + b[3] = (byte) (val >>> 0); + b[2] = (byte) (val >>> 8); + b[1] = (byte) (val >>> 16); + b[0] = (byte) (val >>> 24); + return b; + } + + static byte[] getBytes(long val) { + byte[] b = new byte[8]; + b[7] = (byte) (val >>> 0); + b[6] = (byte) (val >>> 8); + b[5] = (byte) (val >>> 16); + b[4] = (byte) (val >>> 24); + b[3] = (byte) (val >>> 32); + b[2] = (byte) (val >>> 40); + b[1] = (byte) (val >>> 48); + b[0] = (byte) (val >>> 56); + return b; + } } diff --git a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/OverlayTransport.java b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/OverlayTransport.java index 9ad34c81..8cdb2c01 100644 --- a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/OverlayTransport.java +++ b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/OverlayTransport.java @@ -9,7 +9,6 @@ import java.util.LinkedList; import java.util.List; import java.util.Random; -import java.util.TimerTask; import java.util.logging.Logger; import org.bouncycastle.util.encoders.Base64; @@ -20,7 +19,6 @@ import org.gudy.azureus2.core3.peer.impl.PEPeerTransport; import org.gudy.azureus2.core3.peer.impl.PEPeerTransportFactory; import org.gudy.azureus2.core3.util.AENetworkClassifier; -import org.gudy.azureus2.core3.util.Average; import org.gudy.azureus2.core3.util.Debug; import org.gudy.azureus2.core3.util.DirectByteBuffer; import org.gudy.azureus2.core3.util.DirectByteBufferPool; @@ -30,7 +28,6 @@ import com.aelitis.azureus.core.networkmanager.ConnectionEndpoint; import com.aelitis.azureus.core.networkmanager.EventWaiter; import com.aelitis.azureus.core.networkmanager.NetworkConnection; -import com.aelitis.azureus.core.networkmanager.NetworkManager; import com.aelitis.azureus.core.networkmanager.ProtocolEndpoint; import com.aelitis.azureus.core.networkmanager.Transport; import com.aelitis.azureus.core.networkmanager.TransportEndpoint; @@ -38,211 +35,63 @@ import com.aelitis.azureus.core.peermanager.messaging.bittorrent.BTMessageDecoder; import com.aelitis.azureus.core.peermanager.messaging.bittorrent.BTMessageEncoder; -import edu.washington.cs.oneswarm.f2f.Friend; import edu.washington.cs.oneswarm.f2f.OSF2FAzSwtUi; import edu.washington.cs.oneswarm.f2f.messaging.OSF2FChannelDataMsg; -import edu.washington.cs.oneswarm.f2f.messaging.OSF2FChannelReset; import edu.washington.cs.oneswarm.f2f.messaging.OSF2FMessage; -import edu.washington.cs.oneswarm.f2f.network.DelayedExecutorService.DelayedExecutor; import edu.washington.cs.oneswarm.f2f.share.DownloadManagerStarter; import edu.washington.cs.oneswarm.f2f.share.DownloadManagerStarter.DownloadManagerStartListener; -public class OverlayTransport implements Transport { +public class OverlayTransport extends OverlayEndpoint implements Transport { - private final static Logger logger = Logger.getLogger(OverlayTransport.class.getName()); - - class OverlayProtocolEndpoint implements ProtocolEndpoint { - private ConnectionEndpoint connectionEndpoint; - - public OverlayProtocolEndpoint() { - connectionEndpoint = new ConnectionEndpoint(getRandomAddr()); - } - - public Transport connectOutbound(boolean connect_with_crypto, boolean allow_fallback, - byte[][] shared_secrets, ByteBuffer initial_data, boolean high_priority, - ConnectListener listener) { - Debug.out(""tried to create outgoing OverlayTransport, this should never happen!!!""); - throw new RuntimeException(""not implemented""); - } - - public Transport connectOutbound(boolean connect_with_crypto, boolean allow_fallback, - byte[][] shared_secrets, ByteBuffer initial_data, ConnectListener listener) { - Debug.out(""tried to create outgoing OverlayTransport, this should never happen!!!""); - throw new RuntimeException(""not implemented""); - } - - public ConnectionEndpoint getConnectionEndpoint() { - return connectionEndpoint; - } - - public String getDescription() { - return ""PROTOCOL_TCP""; - } - - public int getType() { - return PROTOCOL_TCP; - } - - public void setConnectionEndpoint(ConnectionEndpoint ce) { - this.connectionEndpoint = ce; - } - } - - interface WriteQueueWaiter { - public void readyForWrite(); - } - - /* - * max number of ms that a message can be delivered earlier than - * overlayDelayMs if that avoids a call to Thread.sleep() - */ - private final static int INCOMING_MESSAGE_DELAY_SLACK = 10; + static final String chars = ""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789""; - public final static byte[] ID_BYTES = new String(""-OS-F2F-"").getBytes(); - private final static int HANDSHAKE_RESERVED_BITS_START_POS = 20; - private final static int HANDSHAKE_RESERVED_BITS_END_POS = 28; - private final static int HANDSHAKE_INFO_HASH_START_POS = 28; private final static int HANDSHAKE_INFO_HASH_END_POS = 48; + private final static int HANDSHAKE_INFO_HASH_START_POS = 28; private final static int HANDSHAKE_PEER_ID_POS = 48; - private static final int HANDSHAKE_END_POS = HANDSHAKE_PEER_ID_POS + 20; + private final static int HANDSHAKE_RESERVED_BITS_END_POS = 28; + private final static int HANDSHAKE_RESERVED_BITS_START_POS = 20; + public final static byte[] ID_BYTES = new String(""-OS-F2F-"").getBytes(); private final static int HANDSHAKE_PEER_ID_KEEP = ID_BYTES.length; + private static final int HANDSHAKE_END_POS = HANDSHAKE_PEER_ID_POS + 20; private static final int HANDSHAKE_PEER_ID_START_MOD_POS = HANDSHAKE_PEER_ID_POS + HANDSHAKE_PEER_ID_KEEP; - public static InetSocketAddress getRandomAddr() { - byte[] randomAddr = new byte[16]; - randomAddr[0] = (byte) 0xfc; - randomAddr[1] = 0; - Random r = new Random(); - byte[] rand = new byte[randomAddr.length - 2]; - r.nextBytes(rand); - System.arraycopy(rand, 0, randomAddr, 2, rand.length); - InetAddress addr; - try { - addr = InetAddress.getByAddress(randomAddr); - InetSocketAddress remoteFakeAddr = new InetSocketAddress(addr, 1); - return remoteFakeAddr; - } catch (UnknownHostException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return null; - } - - private ByteBuffer data_already_read = null; - - protected boolean closed = false; - private String closeReason = """"; - private boolean sentReset = false; - private final int TIMEOUT = 2 * 60 * 1000; - private long lastMsgTime; - - private final byte[] infoHash; - private final long startTime; - private boolean started = false; - private final int channelId; + private final static Logger logger = Logger.getLogger(OverlayTransport.class.getName()); - private final int pathID; // all operations on this object must be in a synchronized block private final LinkedList bufferedMessages; - protected final FriendConnection connection; - - private List readWaiter = new LinkedList(); - private List writeWaiter = new LinkedList(); + private final byte[] channelPeerId; + private ByteBuffer data_already_read = null; - private int transport_mode; + private final byte[] infoHash; + private volatile boolean outgoing; private int posInHandshake = 0; - private byte[] remoteHandshakeInfoHashBytes = new byte[20]; - private volatile boolean remoteHandshakeRecieved; - private volatile boolean outgoing; + private List readWaiter = new LinkedList(); - private final byte[] channelPeerId; + private byte[] remoteHandshakeInfoHashBytes = new byte[20]; - private long bytesIn = 0; - private long bytesOut = 0; - private Average uploadRateAverage = Average.getInstance(1000, 10); - private Average downloadRateAverage = Average.getInstance(1000, 10); + private volatile boolean remoteHandshakeRecieved; - private final long overlayDelayMs; + private int transport_mode; - private final DelayedExecutor delayedOverlayMessageTimer; + private List writeWaiter = new LinkedList(); public OverlayTransport(FriendConnection connection, int channelId, byte[] infohash, int pathID, boolean outgoing, long overlayDelayMs) { - this.lastMsgTime = System.currentTimeMillis(); - this.overlayDelayMs = overlayDelayMs; + super(connection, channelId, pathID, overlayDelayMs); this.infoHash = infohash; this.bufferedMessages = new LinkedList(); - this.connection = connection; - this.channelId = channelId; logger.fine(getDescription() + "": Creating overlay transport""); this.channelPeerId = generatePeerId(); - this.pathID = pathID; this.outgoing = outgoing; - this.startTime = System.currentTimeMillis(); - delayedOverlayMessageTimer = DelayedExecutorService.getInstance().getFixedDelayExecutor( - overlayDelayMs); } - /** - * This method is called ""from above"", when the peer connection is - * terminated, send a reset to other side - */ - public void close(String reason) { - if (!closed) { - closeReason = ""peer - "" + reason; - logger.fine(getDescription() + "": OverlayTransport closed, reason:"" + closeReason); - - closed = true; - this.sendReset(); - } - // we don't expect anyone to read whatever we have left in the buffer - synchronized (bufferedMessages) { - while (bufferedMessages.size() > 0) { - bufferedMessages.removeFirst().destroy(); - } - } - // and remove it from the friend connection - connection.deregisterOverlayTransport(this); - - } - - /** - * this method is called from below when a reset is received - * - * @param reason - */ - public void closeChannelReset() { - - if (sentReset) { - // ok, this is the response to our previous close - connection.deregisterOverlayTransport(this); - } else { - if (!closed) { - closeReason = ""remote host closed overlay channel""; - logger.fine(getDescription() + "": OverlayTransport closed, reason:"" + closeReason); - // this is the remote side saying that the connection is closed - // send a reset back to confirm - sendReset(); - closed = true; - } - } - } - - /** - * this method is called from below if the friend connection dies - * - * @param reason - */ - public void closeConnectionClosed(String reason) { - closeReason = reason; - logger.fine(getDescription() + "": OverlayTransport closed, reason:"" + closeReason); - - closed = true; - connection.deregisterOverlayTransport(this); + @Override + protected void cleanup() { + // not used. } public void connectedInbound() { @@ -258,7 +107,43 @@ public void connectOutbound(ByteBuffer initial_data, ConnectListener listener, throw new RuntimeException(""not implemented""); } - static final String chars = ""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789""; + private void createPeerTransport(DownloadManager downloadManager) { + // final check, we only allow this if the osf2f network is enabled, and + // osf2f friend search is a valid peer source + boolean allowed = checkOSF2FAllowed(downloadManager.getDownloadState().getPeerSources(), + downloadManager.getDownloadState().getNetworks()); + + if (!allowed) { + Debug.out(""denied request to create a peer""); + this.closeConnectionClosed(""access denied when creating overlay""); + return; + } + + PEPeerManager manager = downloadManager.getPeerManager(); + + PEPeerControl control = (PEPeerControl) manager; + // set it up the same way as an incoming connection + final NetworkConnection overlayConn = new NetworkConnectionImpl(this, + new BTMessageEncoder(), new BTMessageDecoder()); + PEPeerTransport pt = PEPeerTransportFactory.createTransport(control, PEPeerSource.PS_OSF2F, + overlayConn, null); + + // start it + pt.start(); + // and add it to the control + control.addPeerTransport(pt); + + // add the friend + pt.setData(OSF2FAzSwtUi.KEY_OVERLAY_TRANSPORT, this); + } + + protected void destroyBufferedMessages() { + synchronized (bufferedMessages) { + while (bufferedMessages.size() > 0) { + bufferedMessages.removeFirst().destroy(); + } + } + } public byte[] generatePeerId() { byte[] peerId = new byte[20]; @@ -272,20 +157,6 @@ public byte[] generatePeerId() { return peerId; } - public int getChannelId() { - return channelId; - } - - private String desc = null; - - public String getDescription() { - if (desc == null) { - desc = NetworkManager.OSF2F_TRANSPORT_PREFIX + "": "" - + connection.getRemoteFriend().getNick() + "":"" + Integer.toHexString(channelId); - } - return desc; - } - public String getEncryption() { return (""FriendToFriend over SSL""); } @@ -294,10 +165,6 @@ public int getMssSize() { return OSF2FMessage.MAX_MESSAGE_SIZE; } - public int getPathID() { - return pathID; - } - public TransportEndpoint getTransportEndpoint() { return new TransportEndpoint() { @@ -315,21 +182,7 @@ public int getTransportMode() { return transport_mode; } - public void incomingOverlayMsg(final OSF2FChannelDataMsg msg) { - lastMsgTime = System.currentTimeMillis(); - if (closed) { - return; - } - delayedOverlayMessageTimer.queue(overlayDelayMs, INCOMING_MESSAGE_DELAY_SLACK, - new TimerTask() { - @Override - public void run() { - handleDelayedOverlayMessage(msg); - } - }); - } - - private void handleDelayedOverlayMessage(final OSF2FChannelDataMsg msg) { + protected void handleDelayedOverlayMessage(final OSF2FChannelDataMsg msg) { synchronized (bufferedMessages) { bufferedMessages.add(msg); @@ -381,7 +234,7 @@ public boolean isReadyForWrite(final EventWaiter waiter) { if (closed) { return false; } - if (!connection.isReadyForWrite(new WriteQueueWaiter() { + if (!friendConnection.isReadyForWrite(new WriteQueueWaiter() { public void readyForWrite() { if (waiter != null) { logger.finest(getDescription() + "": connection ready, notifying waiter""); @@ -396,18 +249,10 @@ public void readyForWrite() { return true; } - public boolean isStarted() { - return started; - } - public boolean isTCP() { return true; } - public boolean isTimedOut() { - return System.currentTimeMillis() - lastMsgTime > TIMEOUT; - } - private byte modifyIncomingHandShake(byte b) { if (posInHandshake == -1) { return b; @@ -428,7 +273,7 @@ private byte modifyIncomingHandShake(byte b) { if (!Arrays.equals(infoHash, remoteHandshakeInfoHashBytes)) { logger.warning(getDescription() + "": WARNING in "" - + connection + + friendConnection + "" :: remote host different infohash "" + ""than what we expected ,expected:\n "" + new String(Base64.encode(infoHash) + "" got\n"" @@ -584,12 +429,6 @@ public long read(ByteBuffer[] buffers, int array_offset, int length) throws IOEx return totalRead; } - public void sendReset() { - sentReset = true; - connection.sendChannelRst(new OSF2FChannelReset(OSF2FChannelReset.CURRENT_VERSION, - channelId)); - } - public void setAlreadyRead(ByteBuffer bytes_already_read) { if (data_already_read != null) { Debug.out(""push back already performed""); @@ -631,38 +470,31 @@ public void downloadStarted() { }); } - public long getArtificialDelay() { - return overlayDelayMs; - } - - private void createPeerTransport(DownloadManager downloadManager) { - // final check, we only allow this if the osf2f network is enabled, and - // osf2f friend search is a valid peer source - boolean allowed = checkOSF2FAllowed(downloadManager.getDownloadState().getPeerSources(), - downloadManager.getDownloadState().getNetworks()); - - if (!allowed) { - Debug.out(""denied request to create a peer""); - this.closeConnectionClosed(""access denied when creating overlay""); - return; + public long write(ByteBuffer[] buffers, int array_offset, int length) throws IOException { + if (closed) { + // when closed just ignore the write requests + // hopefully the peertransport will read everything in the buffer + // and get the exception there when done + return 0; } - - PEPeerManager manager = downloadManager.getPeerManager(); - - PEPeerControl control = (PEPeerControl) manager; - // set it up the same way as an incoming connection - final NetworkConnection overlayConn = new NetworkConnectionImpl(this, - new BTMessageEncoder(), new BTMessageDecoder()); - PEPeerTransport pt = PEPeerTransportFactory.createTransport(control, PEPeerSource.PS_OSF2F, - overlayConn, null); - - // start it - pt.start(); - // and add it to the control - control.addPeerTransport(pt); - - // add the friend - pt.setData(OSF2FAzSwtUi.KEY_OVERLAY_TRANSPORT, this); + int totalToWrite = 0; + int totalWritten = 0; + for (int i = array_offset; i < array_offset + length; i++) { + totalToWrite += buffers[i].remaining(); + } + logger.finest(getDescription() + ""got write request for: "" + totalToWrite); + // only write one packet at the time + if (isReadyForWrite(null)) { + DirectByteBuffer msgBuffer = DirectByteBufferPool.getBuffer(DirectByteBuffer.AL_MSG, + Math.min(totalToWrite, OSF2FMessage.MAX_PAYLOAD_SIZE)); + this.putInBuffer(buffers, array_offset, length, msgBuffer); + msgBuffer.flip(DirectByteBuffer.SS_MSG); + totalWritten += writeMessageToFriendConnection(msgBuffer); + } + logger.finest(""wrote "" + totalWritten + "" to overlay channel "" + channelId); + bytesOut += totalWritten; + uploadRateAverage.addValue(totalWritten); + return totalWritten; } /** @@ -697,76 +529,64 @@ public static boolean checkOSF2FAllowed(String[] peerSources, String[] netSource return allowed; } - public long write(ByteBuffer[] buffers, int array_offset, int length) throws IOException { - if (closed) { - // when closed just ignore the write requests - // hopefully the peertransport will read everything in the buffer - // and get the exception there when done - return 0; - } - int totalToWrite = 0; - int totalWritten = 0; - for (int i = array_offset; i < array_offset + length; i++) { - totalToWrite += buffers[i].remaining(); - } - logger.finest(getDescription() + ""got write request for: "" + totalToWrite); - // only write one packet at the time - if (isReadyForWrite(null)) { - DirectByteBuffer msgBuffer = DirectByteBufferPool.getBuffer(DirectByteBuffer.AL_MSG, - Math.min(totalToWrite, OSF2FMessage.MAX_PAYLOAD_SIZE)); - this.putInBuffer(buffers, array_offset, length, msgBuffer); - msgBuffer.flip(DirectByteBuffer.SS_MSG); - totalWritten += writeMessage(msgBuffer); + public static InetSocketAddress getRandomAddr() { + byte[] randomAddr = new byte[16]; + randomAddr[0] = (byte) 0xfc; + randomAddr[1] = 0; + Random r = new Random(); + byte[] rand = new byte[randomAddr.length - 2]; + r.nextBytes(rand); + System.arraycopy(rand, 0, randomAddr, 2, rand.length); + InetAddress addr; + try { + addr = InetAddress.getByAddress(randomAddr); + InetSocketAddress remoteFakeAddr = new InetSocketAddress(addr, 1); + return remoteFakeAddr; + } catch (UnknownHostException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } - logger.finest(""wrote "" + totalWritten + "" to overlay channel "" + channelId); - bytesOut += totalWritten; - uploadRateAverage.addValue(totalWritten); - return totalWritten; - } - - protected long writeMessage(DirectByteBuffer msgBuffer) { - OSF2FChannelDataMsg msg = new OSF2FChannelDataMsg(OSF2FMessage.CURRENT_VERSION, channelId, - msgBuffer); - long totalWritten = msgBuffer.remaining(DirectByteBuffer.SS_MSG); - msg.setForward(false); - connection.sendChannelMsg(msg, true); - return totalWritten; + return null; } - public String getRemoteIP() { - return connection.getRemoteIp().getHostAddress(); - } + private static class OverlayProtocolEndpoint implements ProtocolEndpoint { + private ConnectionEndpoint connectionEndpoint; - public Friend getRemoteFriend() { - return connection.getRemoteFriend(); - } + public OverlayProtocolEndpoint() { + connectionEndpoint = new ConnectionEndpoint(getRandomAddr()); + } - public long getAge() { - return System.currentTimeMillis() - startTime; - } + public Transport connectOutbound(boolean connect_with_crypto, boolean allow_fallback, + byte[][] shared_secrets, ByteBuffer initial_data, boolean high_priority, + ConnectListener listener) { + Debug.out(""tried to create outgoing OverlayTransport, this should never happen!!!""); + throw new RuntimeException(""not implemented""); + } - public long getLastMsgTime() { - return System.currentTimeMillis() - lastMsgTime; - } + public Transport connectOutbound(boolean connect_with_crypto, boolean allow_fallback, + byte[][] shared_secrets, ByteBuffer initial_data, ConnectListener listener) { + Debug.out(""tried to create outgoing OverlayTransport, this should never happen!!!""); + throw new RuntimeException(""not implemented""); + } - public long getBytesIn() { - return bytesIn; - } + public ConnectionEndpoint getConnectionEndpoint() { + return connectionEndpoint; + } - public long getBytesOut() { - return bytesOut; - } + public String getDescription() { + return ""PROTOCOL_TCP""; + } - public int getUploadRate() { - return (int) uploadRateAverage.getAverage(); - } + public int getType() { + return PROTOCOL_TCP; + } - public int getDownloadRate() { - return (int) downloadRateAverage.getAverage(); + public void setConnectionEndpoint(ConnectionEndpoint ce) { + this.connectionEndpoint = ce; + } } - public boolean isLANLocal() { - return connection.getNetworkConnection().isLANLocal(); + interface WriteQueueWaiter { + public void readyForWrite(); } - } diff --git a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/OverlayTransportEncrypted.java b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/OverlayTransportEncrypted.java index 0a210a17..ae86c793 100644 --- a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/OverlayTransportEncrypted.java +++ b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/OverlayTransportEncrypted.java @@ -17,97 +17,103 @@ import edu.washington.cs.oneswarm.f2f.messaging.OSF2FMessage; public class OverlayTransportEncrypted extends OverlayTransport { - private final static Logger logger = Logger.getLogger(OverlayTransportEncrypted.class.getName()); + private final static Logger logger = Logger + .getLogger(OverlayTransportEncrypted.class.getName()); - private static final String ENCRYPTION_ALGORITHM = ""AES/CFB/NoPadding""; - public final static int KEY_LENGTH_BITS = 256; - final Cipher readCipher; - final Cipher writeCipher; + private static final String ENCRYPTION_ALGORITHM = ""AES/CFB/NoPadding""; + public final static int KEY_LENGTH_BITS = 256; + final Cipher readCipher; + final Cipher writeCipher; - public OverlayTransportEncrypted(FriendConnection connection, int channelId, byte[] infohash, int pathID, boolean outgoing, long overlayDelayMs, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { - super(connection, channelId, infohash, pathID, outgoing, overlayDelayMs); - if (key.length / 8 != KEY_LENGTH_BITS) { - throw new InvalidKeyException(""invalid key length""); - } + public OverlayTransportEncrypted(FriendConnection connection, int channelId, byte[] infohash, + int pathID, boolean outgoing, long overlayDelayMs, byte[] key) + throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { + super(connection, channelId, infohash, pathID, outgoing, overlayDelayMs); + if (key.length / 8 != KEY_LENGTH_BITS) { + throw new InvalidKeyException(""invalid key length""); + } - SecretKeySpec keySpec = new SecretKeySpec(key, 0, key.length, ENCRYPTION_ALGORITHM); - readCipher = Cipher.getInstance(ENCRYPTION_ALGORITHM); - readCipher.init(Cipher.DECRYPT_MODE, keySpec); - writeCipher = Cipher.getInstance(ENCRYPTION_ALGORITHM); - writeCipher.init(Cipher.ENCRYPT_MODE, keySpec); - } + SecretKeySpec keySpec = new SecretKeySpec(key, 0, key.length, ENCRYPTION_ALGORITHM); + readCipher = Cipher.getInstance(ENCRYPTION_ALGORITHM); + readCipher.init(Cipher.DECRYPT_MODE, keySpec); + writeCipher = Cipher.getInstance(ENCRYPTION_ALGORITHM); + writeCipher.init(Cipher.ENCRYPT_MODE, keySpec); + } - public long write(ByteBuffer[] buffers, int array_offset, int length) throws IOException { + public long write(ByteBuffer[] buffers, int array_offset, int length) throws IOException { - if (closed) { - // when closed just ignore the write requests - // hopefully the peertransport will read everything in the - // buffer - // and get the exception there when done - return 0; - } - int totalToWrite = 0; - int totalWritten = 0; - try { - for (int i = array_offset; i < array_offset + length; i++) { - totalToWrite += buffers[i].remaining(); - } - logger.finest(getDescription() + ""got write request for: "" + totalToWrite); - // only write one packet at the time - if (isReadyForWrite(null)) { - DirectByteBuffer msgBuffer = DirectByteBufferPool.getBuffer(DirectByteBuffer.AL_MSG, Math.min(totalToWrite, OSF2FMessage.MAX_PAYLOAD_SIZE)); + if (closed) { + // when closed just ignore the write requests + // hopefully the peertransport will read everything in the + // buffer + // and get the exception there when done + return 0; + } + int totalToWrite = 0; + int totalWritten = 0; + try { + for (int i = array_offset; i < array_offset + length; i++) { + totalToWrite += buffers[i].remaining(); + } + logger.finest(getDescription() + ""got write request for: "" + totalToWrite); + // only write one packet at the time + if (isReadyForWrite(null)) { + DirectByteBuffer msgBuffer = DirectByteBufferPool.getBuffer( + DirectByteBuffer.AL_MSG, + Math.min(totalToWrite, OSF2FMessage.MAX_PAYLOAD_SIZE)); - ByteBuffer dstBuffer = msgBuffer.getBuffer(DirectByteBuffer.SS_MSG); - for (int i = 0; i < buffers.length; i++) { - ByteBuffer currBuffer = buffers[i]; + ByteBuffer dstBuffer = msgBuffer.getBuffer(DirectByteBuffer.SS_MSG); + for (int i = 0; i < buffers.length; i++) { + ByteBuffer currBuffer = buffers[i]; - if (currBuffer.remaining() > dstBuffer.remaining()) { - // we have more to write than what we can fit - // set the limit of the source to reflect this - int oldLimit = currBuffer.limit(); - int newLimit = currBuffer.position() + dstBuffer.remaining(); - currBuffer.limit(newLimit); - writeCipher.update(currBuffer, dstBuffer); - // and restore the limit when done - currBuffer.limit(oldLimit); - break; - } else { - writeCipher.update(currBuffer, dstBuffer); - } - } - msgBuffer.flip(DirectByteBuffer.SS_MSG); - totalWritten += writeMessage(msgBuffer); - } - } catch (ShortBufferException e) { - logger.warning(""not enough room in the destination buffer, this should NEVER happen!""); - e.printStackTrace(); - super.close(""short buffer exception""); - } + if (currBuffer.remaining() > dstBuffer.remaining()) { + // we have more to write than what we can fit + // set the limit of the source to reflect this + int oldLimit = currBuffer.limit(); + int newLimit = currBuffer.position() + dstBuffer.remaining(); + currBuffer.limit(newLimit); + writeCipher.update(currBuffer, dstBuffer); + // and restore the limit when done + currBuffer.limit(oldLimit); + break; + } else { + writeCipher.update(currBuffer, dstBuffer); + } + } + msgBuffer.flip(DirectByteBuffer.SS_MSG); + totalWritten += writeMessageToFriendConnection(msgBuffer); + } + } catch (ShortBufferException e) { + logger.warning(""not enough room in the destination buffer, this should NEVER happen!""); + e.printStackTrace(); + super.close(""short buffer exception""); + } - return totalWritten; - } + return totalWritten; + } - public long read(ByteBuffer[] buffers, int array_offset, int length) throws IOException { - DirectByteBuffer[] tempBufferPool = new DirectByteBuffer[buffers.length]; - ByteBuffer[] tempBuffers = new ByteBuffer[buffers.length]; - for (int i = 0; i < buffers.length; i++) { - tempBufferPool[i] = DirectByteBufferPool.getBuffer(DirectByteBuffer.AL_MSG, buffers[i].remaining()); - tempBuffers[i] = tempBufferPool[i].getBuffer(DirectByteBuffer.SS_MSG); - } - long len = super.read(tempBuffers, array_offset, length); - try { - for (int i = 0; i < tempBuffers.length; i++) { - readCipher.update(tempBuffers[i], buffers[i]); - tempBufferPool[i].returnToPool(); - } - } catch (ShortBufferException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return len; - } + public long read(ByteBuffer[] buffers, int array_offset, int length) throws IOException { + DirectByteBuffer[] tempBufferPool = new DirectByteBuffer[buffers.length]; + ByteBuffer[] tempBuffers = new ByteBuffer[buffers.length]; + for (int i = 0; i < buffers.length; i++) { + tempBufferPool[i] = DirectByteBufferPool.getBuffer(DirectByteBuffer.AL_MSG, + buffers[i].remaining()); + tempBuffers[i] = tempBufferPool[i].getBuffer(DirectByteBuffer.SS_MSG); + } + long len = super.read(tempBuffers, array_offset, length); + try { + for (int i = 0; i < tempBuffers.length; i++) { + readCipher.update(tempBuffers[i], buffers[i]); + tempBufferPool[i].returnToPool(); + } + } catch (ShortBufferException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return len; + } - public String getDescription() { - return ""ENCR: "" + super.getDescription(); - } + public String getDescription() { + return ""ENCR: "" + super.getDescription(); + } } diff --git a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/SearchManager.java b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/SearchManager.java index 85eeb392..6095107d 100644 --- a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/SearchManager.java +++ b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/SearchManager.java @@ -57,1603 +57,1711 @@ import edu.washington.cs.oneswarm.f2f.network.DelayedExecutorService.DelayedExecutionEntry; import edu.washington.cs.oneswarm.f2f.network.DelayedExecutorService.DelayedExecutor; import edu.washington.cs.oneswarm.f2f.network.FriendConnection.OverlayRegistrationError; +import edu.washington.cs.oneswarm.f2f.servicesharing.ServiceSharingManager; +import edu.washington.cs.oneswarm.f2f.servicesharing.ServiceSharingManager.SharedService; import edu.washington.cs.oneswarm.f2f.share.ShareManagerTools; import edu.washington.cs.oneswarm.ui.gwt.BackendErrorLog; public class SearchManager { - public static final String SEARCH_QUEUE_THREAD_NAME = ""DelayedSearchQueue""; - - private final static BigFatLock lock = OverlayManager.lock; - private static Logger logger = Logger.getLogger(SearchManager.class.getName()); - // search sources are remembered for 1 minute, any replies after this will - // be dropped - public static final long MAX_SEARCH_AGE = 60 * 1000; - public static final int MAX_SEARCH_QUEUE_LENGTH = 100; -// private static final int MAX_SEARCH_RESP_BEFORE_CANCEL = COConfigurationManager.getIntParameter(""f2f_search_max_paths""); - - protected int mMaxSearchResponsesBeforeCancel = COConfigurationManager.getIntParameter(""f2f_search_max_paths""); - - // don't respond if average torrent upload rate is less than 10K/s - private static final double NO_RESPONSE_TORRENT_AVERAGE_RATE = 10000; - - private static final double NO_RESPONSE_TOTAL_FRAC_OF_MAX_UPLOAD = 0.9; - - private static final double NO_RESPONSE_TRANSPORT_FRAC_OF_MAX_UPLOAD = 0.75; - /* - * this is to avoid searches living forever, search uid are remembered for - * 45min-1h, there are 4 bloom filter buckets that are rotating, each one - * containing 15minutes worth of searches - */ - private static final int RECENT_SEARCH_BUCKETS = 4; - - private static final long RECENT_SEARCH_MEMORY = 20 * 60 * 1000; -// static final int SEARCH_DELAY = COConfigurationManager.getIntParameter(""f2f_search_forward_delay""); - protected int mSearchDelay = COConfigurationManager.getIntParameter(""f2f_search_forward_delay""); - - /** - * This Map is protected by the BigFatLock: lock. We use this to drop searches from friends - * that are crowding the outgoing search queue early, thus allowing friends that send searches - * more rarely to get through. - * - * This map is emptied once every 60 seconds to deal with accounting errors that may accumulate. - */ - class MutableInteger { public int v=0; } - long lastSearchAccountingFlush = System.currentTimeMillis(); - private final Map searchesPerFriend = new HashMap(); - - private int bloomSearchesBlockedCurr = 0; - - private int bloomSearchesBlockedPrev = 0; - private int bloomSearchesSentCurr = 0; - private int bloomSearchesSentPrev = 0; - - private final HashMap canceledSearches; - private final DebugChannelSetupErrorStats debugChannelIdErrorSetupErrorStats = new DebugChannelSetupErrorStats(); - - private final DelayedSearchQueue delayedSearchQueue; - - // private final DeterministicDelayResponseQueue delayedResponseQueue; - - private final FileListManager filelistManager; - - private final HashMap forwardedSearches; - private int forwardedSearchNum = 0; - private List hashSearchStats = new LinkedList(); - - private boolean includeLanUploads; - private final double NO_FORWARD_FRAC_OF_MAX_UPLOAD = 0.9; - private final OverlayManager overlayManager; - - private final Random random = new Random(); - private final RandomnessManager randomnessManager; - - private int rateLimitInKBps; - - private final RotatingBloomFilter recentSearches; - private final HashMap sentSearches; - private final GlobalManagerStats stats; - private final TextSearchManager textSearchManager; - - private List textSearchStats = new LinkedList(); - - private final DelayedExecutor delayedExecutor; - - private String[] filteredKeywords = new String[0]; - - public SearchManager(OverlayManager overlayManager, FileListManager filelistManager, RandomnessManager randomnessManager, GlobalManagerStats stats) { - this.stats = stats; - this.delayedExecutor = DelayedExecutorService.getInstance().getVariableDelayExecutor(); - // this.delayedResponseQueue = new DeterministicDelayResponseQueue(); - this.overlayManager = overlayManager; - this.sentSearches = new HashMap(); - this.forwardedSearches = new HashMap(); - this.canceledSearches = new HashMap(); - this.filelistManager = filelistManager; - this.randomnessManager = randomnessManager; - this.textSearchManager = new TextSearchManager(); - this.recentSearches = new RotatingBloomFilter(RECENT_SEARCH_MEMORY, RECENT_SEARCH_BUCKETS); - this.delayedSearchQueue = new DelayedSearchQueue(mSearchDelay); - COConfigurationManager.addAndFireParameterListeners(new String[] { ""LAN Speed Enabled"", ""Max Upload Speed KBs"", ""oneswarm.search.filter.keywords"", - ""f2f_search_max_paths"", ""f2f_search_forward_delay"" }, new ParameterListener() { - public void parameterChanged(String parameterName) { - includeLanUploads = !COConfigurationManager.getBooleanParameter(""LAN Speed Enabled""); - rateLimitInKBps = COConfigurationManager.getIntParameter(""Max Upload Speed KBs""); - - StringList keywords = COConfigurationManager.getStringListParameter(""oneswarm.search.filter.keywords""); - if (keywords != null) { - String[] neu = new String[keywords.size()]; - for (int i = 0; i < keywords.size(); i++) { - String firstTok = (new StringTokenizer(keywords.get(i))).nextToken(); - neu[i] = firstTok; - } - filteredKeywords = neu; - logger.fine(""Updated filtered keywords "" + keywords.size()); - } - - mMaxSearchResponsesBeforeCancel = COConfigurationManager.getIntParameter(""f2f_search_max_paths""); - - mSearchDelay = COConfigurationManager.getIntParameter(""f2f_search_forward_delay""); - delayedSearchQueue.setDelay(mSearchDelay); - } - }); - } - - private boolean canForwardSearch() { - double util = fracUpload(); - if (util == -1 || util < NO_FORWARD_FRAC_OF_MAX_UPLOAD) { - return true; - } else { - logger.finest(""not forwarding search (overloaded, util="" + util + "")""); - return false; - } - } - - private boolean canRespondToSearch() { - double totalUtil = fracUpload(); - if (totalUtil == -1) { - return true; - } - // ok, check if we are using more than 90% of total - if (totalUtil < NO_RESPONSE_TOTAL_FRAC_OF_MAX_UPLOAD) { - return true; - } - double transUtil = fracTransportUpload(); - // check if we are using more than 75% for transports - if (transUtil < NO_RESPONSE_TRANSPORT_FRAC_OF_MAX_UPLOAD) { - return true; - } - - double torrentAvgSpeed = getAverageUploadPerRunningTorrent(); - if (torrentAvgSpeed == -1) { - return true; - } - if (torrentAvgSpeed > NO_RESPONSE_TORRENT_AVERAGE_RATE) { - return true; - } - if (logger.isLoggable(Level.FINER)) { - logger.finer(""not responding to search (overloaded, util="" + transUtil + "")""); - } - return false; - } - - public void clearTimedOutSearches() { - lock.lock(); - try { - /* - * check if we need to rotate the bloom filter of recent searches - */ - boolean rotated = recentSearches.rotateIfNeeded(); - if (rotated) { - bloomSearchesBlockedPrev = bloomSearchesBlockedCurr; - bloomSearchesBlockedCurr = 0; - bloomSearchesSentPrev = bloomSearchesSentCurr; - bloomSearchesSentCurr = 0; - } - - for (Iterator iterator = forwardedSearches.values().iterator(); iterator.hasNext();) { - ForwardedSearch fs = iterator.next(); - if (fs.isTimedOut()) { - iterator.remove(); - } - } - - for (Iterator iterator = sentSearches.values().iterator(); iterator.hasNext();) { - SentSearch sentSearch = iterator.next(); - if (sentSearch.isTimedOut()) { - iterator.remove(); - if (sentSearch.getSearch() instanceof OSF2FHashSearch) { - hashSearchStats.add(sentSearch.getResponseNum()); - } else if (sentSearch.getSearch() instanceof OSF2FTextSearch) { - textSearchStats.add(sentSearch.getResponseNum()); - } - } - } - - /* - * Delete any expired canceled searches - */ - LinkedList toDelete = new LinkedList(); - for (Integer key : canceledSearches.keySet()) { - long age = System.currentTimeMillis() - canceledSearches.get(key); - if (age > MAX_SEARCH_AGE) { - toDelete.add(key); - } - } - - for (Integer key : toDelete) { - canceledSearches.remove(key); - } - - textSearchManager.clearOldResponses(); - } finally { - lock.unlock(); - } - } - - public List debugCanceledSearches() { - List l = new LinkedList(); - lock.lock(); - try { - for (Integer s : canceledSearches.keySet()) { - l.add(""search="" + Integer.toHexString(s) + "" age="" + ((System.currentTimeMillis() - canceledSearches.get(s)) / 1000) + ""s""); - } - } finally { - lock.unlock(); - } - return l; - } - - public List debugForwardedSearches() { - List l = new LinkedList(); - lock.lock(); - try { - for (ForwardedSearch f : forwardedSearches.values()) { - l.add(""search="" + Integer.toHexString(f.getSearchId()) + "" responses="" + f.getResponseNum() + "" age="" + (f.getAge() / 1000) + ""s""); - } - } finally { - lock.unlock(); - } - return l; - } - - public List debugSentSearches() { - List l = new LinkedList(); - lock.lock(); - try { - for (SentSearch s : sentSearches.values()) { - l.add(""search="" + Integer.toHexString(s.getSearch().getSearchID()) + "" responses="" + s.getResponseNum() + "" age="" + (s.getAge() / 1000) + ""s""); - } - } finally { - lock.unlock(); - } - return l; - } - - private void forwardSearch(FriendConnection source, OSF2FSearch search) { - lock.lock(); - try { - - // check if search is canceled or forwarded first - int searchID = search.getSearchID(); - if (forwardedSearches.containsKey(searchID)) { - logger.finest(""not forwarding search, already forwarded. id: "" + searchID); - return; - } - - if (canceledSearches.containsKey(searchID)) { - logger.finest(""not forwarding search, cancel received. id: "" + searchID); - return; - } - - int valueID = search.getValueID(); - if (recentSearches.contains(searchID, valueID)) { - bloomSearchesBlockedCurr++; - logger.finest(""not forwarding search, in recent filter. id: "" + searchID); - return; - } - bloomSearchesSentCurr++; - forwardedSearchNum++; - if (logger.isLoggable(Level.FINEST)) { - logger.finest(""forwarding search "" + search.getDescription() + "" id: "" + searchID); - } - forwardedSearches.put(searchID, new ForwardedSearch(source, search)); - recentSearches.insert(searchID, valueID); - } finally { - lock.unlock(); - } - - overlayManager.forwardSearchOrCancel(source, search.clone()); - } - - private double fracTransportUpload() { - - if (rateLimitInKBps < 1) { - return -1; - } - long uploadRate = overlayManager.getTransportSendRate(includeLanUploads); - - double util = uploadRate / (rateLimitInKBps * 1024.0); - return util; - } - - private double fracUpload() { - - if (rateLimitInKBps < 1) { - return -1; - } - long uploadRate; - if (!includeLanUploads) { - uploadRate = stats.getProtocolSendRateNoLAN() + stats.getDataSendRateNoLAN(); - } else { - uploadRate = stats.getProtocolSendRate() + stats.getDataSendRate(); - } - - double util = uploadRate / (rateLimitInKBps * 1024.0); - return util; - } - - public int getAndClearForwardedSearchNum() { - lock.lock(); - try { - int ret = forwardedSearchNum; - forwardedSearchNum = 0; - return ret; - } finally { - lock.unlock(); - } - } - - public List getAndClearHashSearchStats() { - lock.lock(); - try { - List ret = hashSearchStats; - hashSearchStats = new LinkedList(); - return ret; - } finally { - lock.unlock(); - } - } - - public List getAndClearTextSearchStats() { - lock.lock(); - try { - List ret = textSearchStats; - textSearchStats = new LinkedList(); - return ret; - } finally { - lock.unlock(); - } - } - - @SuppressWarnings(""unchecked"") - private double getAverageUploadPerRunningTorrent() { - LinkedList dms = new LinkedList(); - final List downloadManagers = AzureusCoreImpl.getSingleton().getGlobalManager().getDownloadManagers(); - dms.addAll(downloadManagers); - - long total = 0; - int num = 0; - - for (DownloadManager dm : dms) { - final DownloadManagerStats s = dm.getStats(); - if (s == null) { - continue; - } - final PEPeerManager p = dm.getPeerManager(); - if (p == null) { - continue; - } - - if (p.getNbPeers() == 0 && p.getNbSeeds() == 0) { - continue; - } - - long uploadRate = s.getDataSendRate() + s.getProtocolSendRate(); - total += uploadRate; - num++; - } - if (num == 0) { - return -1; - } - - return ((double) total) / num; - - } - - public String getSearchDebug() { - StringBuilder b = new StringBuilder(); - b.append(""total_frac="" + fracUpload() + ""\ntransport_frac="" + fracTransportUpload() - + ""\ntorrent_avg="" + getAverageUploadPerRunningTorrent()); - b.append(""\ncan forward="" + canForwardSearch()); - b.append(""\ncan respond="" + canRespondToSearch()); - - b.append(""\n\nforwarded searches size="" + forwardedSearches.size() + "" canceled size="" - + canceledSearches.size() + "" sent size="" + sentSearches.size()); - b.append(""\nbloom: stored="" + recentSearches.getPrevFilterNumElements() - + "" est false positives="" - + (100 * recentSearches.getPrevFilterFalsePositiveEst() + ""%"")); - b.append(""\nbloom blocked|sent curr="" + bloomSearchesBlockedCurr + ""|"" - + bloomSearchesSentCurr + "" prev="" + bloomSearchesBlockedPrev + ""|"" - + bloomSearchesSentPrev); - b.append(""\n\n"" + debugChannelIdErrorSetupErrorStats.getDebugStats()); - - long sum = 0, now = System.currentTimeMillis(), count = 0; - - // Include per-friend queue stats - lock.lock(); - try { - Map counts = new HashMap(); - for (DelayedSearchQueueEntry e : delayedSearchQueue.queuedSearches.values()) { - - count++; - sum += (now - e.insertionTime); - - String nick = e.source.getRemoteFriend().getNick(); - if (counts.containsKey(nick) == false) { - counts.put(nick, new MutableInteger()); - } - counts.get(nick).v++; - } - for (String nick : counts.keySet()) { - b.append(""\n\t"" + nick + "" -> "" + counts.get(nick).v); - } - b.append(""\n\nQueue size: "" + delayedSearchQueue.queuedSearches.size()); - } finally { - lock.unlock(); - } - - b.append(""\nAverage queued search delay: "" + (double)sum/(double)count); - - return b.toString(); - } - - public List getSearchResult(int searchId) { - return textSearchManager.getResults(searchId); - } - - private boolean handleHashSearch(final FriendConnection source, final OSF2FHashSearch msg) { - - // second, we might actually have this data - final byte[] infohash = filelistManager.getMetainfoHash(msg.getInfohashhash()); - - if (infohash != null) { - DownloadManager dm = AzureusCoreImpl.getSingleton().getGlobalManager().getDownloadManager(new HashWrapper(infohash)); - - if (dm != null) { - logger.fine(""found match: "" + new String(Base64.encode(infohash))); - - logger.fine(""found dm match, we have this stuff""); - - // check if the torrent allow osf2f search peers - boolean allowed = OverlayTransport.checkOSF2FAllowed(dm.getDownloadState().getPeerSources(), dm.getDownloadState().getNetworks()); - if (!allowed) { - logger.warning(""got search match for torrent "" + ""that does not allow osf2f peers""); - return true; - } - - boolean completedOrDownloading = FileListManager.completedOrDownloading(dm); - if (!completedOrDownloading) { - return true; - } - - // check if we have the capacity to respond - if (canRespondToSearch() == false) { - return false; - } - - // yeah, we actually have this stuff and we have spare capacity - // create an overlay transport - final int newChannelId = random.nextInt(); - final int transportFakePathId = random.nextInt(); - // set the path id for the overlay transport for something - // random (since otherwise all transports for this infohash will - // get the same pathid, which will limit it to be only one. The - // path id set in the channel setup message will be - // deterministic. It is the responsibility of the source to - // monitor for duplicate paths - - // set the path id to something that will persist between - // searches, for example a deterministic random seeded with - // the infohashhash - final int pathID = randomnessManager.getDeterministicRandomInt((int) msg.getInfohashhash()); - - // get the delay for this overlaytranport, that is the latency - // component of the delay - final int overlayDelay = overlayManager.getLatencyDelayForInfohash(source.getRemoteFriend(), infohash); - - TimerTask task = new TimerTask() { - @Override - public void run() { - try { - /* - * check if the search got canceled while we were - * sleeping - */ - if (!isSearchCanceled(msg.getSearchID())) { - final OSF2FHashSearchResp response = new OSF2FHashSearchResp(OSF2FMessage.CURRENT_VERSION, msg.getSearchID(), newChannelId, pathID); - - final OverlayTransport transp = new OverlayTransport(source, newChannelId, infohash, transportFakePathId, false, overlayDelay); - // register it with the friendConnection - source.registerOverlayTransport(transp); - // send the channel setup message - source.sendChannelSetup(response, false); - } - } catch (OverlayRegistrationError e) { - Debug.out(""got an error when registering incoming transport to '"" + source.getRemoteFriend().getNick() + ""': "" + e.message); - } - } - - }; - delayedExecutor.queue(overlayDelay, task); - - // we are still forwarding if there are files in the torrent - // that we chose not to download - DiskManagerFileInfo[] diskManagerFileInfo = dm.getDiskManagerFileInfo(); - for (DiskManagerFileInfo d : diskManagerFileInfo) { - if (d.isSkipped()) { - return true; - } - } - /* - * ok, we shouldn't forward this, already sent a hash response - * and we have/are downloading all the files - */ - return false; - } - } - - return true; - } - - private boolean isSearchCanceled(int searchId) { - boolean canceled = false; - lock.lock(); - try { - if (canceledSearches.containsKey(searchId)) { - canceled = true; - } - } finally { - lock.unlock(); - } - return canceled; - } - - /** - * Returns the probability of rejecting a search from this friend given the share of the - * overall queue - */ - public double getFriendSearchDropProbability(Friend inFriend) { - - lock.lock(); - try { - - // Always accept if we don't have any searches from friend. - if (searchesPerFriend.get(inFriend) == null) { - return 0; - } - - // Reject proportionally to recent rate. Do not admit more than X/sec. - // Also, proportional to processing queue size. - double rateBound = delayedSearchQueue.searchCount / 80.0; - double queueBound = (double)delayedSearchQueue.queuedSearches.size() / (double)MAX_SEARCH_QUEUE_LENGTH; - - return Math.max(rateBound, queueBound); - - } finally { - lock.unlock(); - } - } - - private void handleIncomingHashSearchResponse(OSF2FHashSearch hashSearch, FriendConnection source, OSF2FHashSearchResp msg) { - // great, we found someone that has what we searched for! - // create the overlay transport - byte[] infoHash = filelistManager.getMetainfoHash(hashSearch.getInfohashhash()); - if (infoHash == null) { - logger.warning(""got channel setup request, "" + ""but the infohash we searched for "" + ""is not in filelistmananger""); - return; - } - - DownloadManager dm = AzureusCoreImpl.getSingleton().getGlobalManager().getDownloadManager(new HashWrapper(infoHash)); - if (dm == null) { - logger.warning(""got channel setup request, "" + ""but the downloadmanager is null""); - return; - } - - if (source.hasRegisteredPath(msg.getPathID())) { - logger.finer(""got channel setup response, "" + ""but path is already used: sending back a reset""); - source.sendChannelRst(new OSF2FChannelReset(OSF2FMessage.CURRENT_VERSION, msg.getChannelID())); - return; - } - - OverlayTransport overlayTransport = new OverlayTransport(source, msg.getChannelID(), infoHash, msg.getPathID(), true, overlayManager.getLatencyDelayForInfohash(source.getRemoteFriend(), infoHash)); - // register it with the friendConnection - try { - source.registerOverlayTransport(overlayTransport); - // safe to start it since we know that the other party is interested - overlayTransport.start(); - } catch (OverlayRegistrationError e) { - Debug.out(""got an error when registering outgoing transport: "" + e.message); - return; - } - - } - - public void handleIncomingSearch(FriendConnection source, OSF2FSearch msg) { - lock.lock(); - try { - logger.finest(""got search: "" + msg.getDescription()); - // first, check if we either sent or forwarded this search before - if (forwardedSearches.containsKey(msg.getSearchID()) || sentSearches.containsKey(msg.getSearchID()) || delayedSearchQueue.isQueued(msg)) { - return; - } - } finally { - lock.unlock(); - } - - boolean shouldForward = true; - // second, check if we actually can do something about this - if (msg instanceof OSF2FHashSearch) { - shouldForward = handleHashSearch(source, (OSF2FHashSearch) msg); - } else if (msg instanceof OSF2FTextSearch) { - shouldForward = handleTextSearch(source, (OSF2FTextSearch) msg); - } else { - logger.warning(""received unrecgonized search type: "" + msg.getID() + "" / "" + msg.getClass().getCanonicalName()); - } - - /* - * check if we are at full capacity - */ - if (canForwardSearch() == false) { - shouldForward = false; - } - - if (shouldForward) { - // ok, seems like we should attempt to forward this, put it in - // the queue - delayedSearchQueue.add(source, msg); - } - - } - - public void handleIncomingSearchCancel(FriendConnection source, OSF2FSearchCancel msg) { - - boolean forward = false; - lock.lock(); - try { - - /* - * if this is the first time we see the cancel, check if we - * forwarded this search, if we did, send a cancel - */ - if (!canceledSearches.containsKey(msg.getSearchID())) { - canceledSearches.put(msg.getSearchID(), System.currentTimeMillis()); - /* - * we only forward the cancel if we already sent the search - */ - if (forwardedSearches.containsKey(msg.getSearchID())) { - forward = true; - } else { - logger.fine(""got search cancel for unknown search id""); - } - } - } finally { - lock.unlock(); - } - if (forward) { - overlayManager.forwardSearchOrCancel(source, msg); - } - } - - /** - * There are 2 possible explanations for getting a search response, either - * we got a response for a search we sent ourselves, or we got a response - * for a search we forwarded - * - * @param source - * connection from where we got the setup - * @param msg - * the channel setup message - */ - public void handleIncomingSearchResponse(FriendConnection source, OSF2FSearchResp msg) { - SentSearch sentSearch; - lock.lock(); - try { - sentSearch = sentSearches.get(msg.getSearchID()); - } finally { - lock.unlock(); - } - // first, if might be a search we sent - if (sentSearch != null) { - logger.finest(""got response to search: "" + sentSearch.getSearch().getDescription()); - OSF2FSearch search = sentSearch.getSearch(); - // update response stats - sentSearch.gotResponse(); - /* - * check if we got enough search responses to cancel this search - * - * we will still use the data, even if the search is canceled. I - * mean, since it already made it here why not use it... - */ - if (sentSearch.getResponseNum() > mMaxSearchResponsesBeforeCancel) { - /* - * only send a cancel message once - */ - boolean sendCancel = false; - lock.lock(); - try { - if (!canceledSearches.containsKey(msg.getSearchID())) { - canceledSearches.put(msg.getSearchID(), System.currentTimeMillis()); - logger.finer(""canceling search "" + msg); - sendCancel = true; - } - } finally { - lock.unlock(); - } - if (sendCancel) { - overlayManager.sendSearchOrCancel(new OSF2FSearchCancel(OSF2FMessage.CURRENT_VERSION, msg.getSearchID()), true, false); - } - } - if (search instanceof OSF2FHashSearch) { - // ok, it was a hash search that we sent - handleIncomingHashSearchResponse((OSF2FHashSearch) search, source, (OSF2FHashSearchResp) msg); - } else if (search instanceof OSF2FTextSearch) { - // this was from a text search we sent - FileList fileList; - try { - OSF2FTextSearchResp textSearchResp = (OSF2FTextSearchResp) msg; - fileList = FileListManager.decode_basic(textSearchResp.getFileList()); - - textSearchManager.gotSearchResponse(search.getSearchID(), source.getRemoteFriend(), fileList, textSearchResp.getChannelID(), source.hashCode()); - - logger.fine(""results so far:""); - List res = getSearchResult(search.getSearchID()); - for (TextSearchResult textSearchResult : res) { - logger.fine(textSearchResult.toString()); - } - } catch (IOException e) { - logger.warning(""got malformed search response""); - } - } else { - logger.warning(""unknown search response type""); - } - } - // sentsearch == null - else { - // ok, this is for a search we forwarded - ForwardedSearch search; - lock.lock(); - try { - search = forwardedSearches.get(msg.getSearchID()); - if (search == null) { - logger.warning(""got response for unknown search:"" + source + "":"" + msg.getDescription()); - return; - } - - logger.finest(""got response to forwarded search: "" + search.getSearch().getDescription()); - - if (canceledSearches.containsKey(msg.getSearchID())) { - logger.finer(""not forwarding search, it is already canceled, "" + msg.getSearchID()); - return; - } - } finally { - lock.unlock(); - } - - FriendConnection searcher = search.getSource(); - FriendConnection responder = source; - - if (search.getResponseNum() > mMaxSearchResponsesBeforeCancel) { - /* - * we really shouldn't cancel other peoples searches, but if - * they don't do it we have to - */ - lock.lock(); - try { - canceledSearches.put(msg.getSearchID(), System.currentTimeMillis()); - } finally { - lock.unlock(); - } - logger.finest(""Sending cancel for someone elses search!, searcher="" + searcher.getRemoteFriend() + "" responder="" + responder.getRemoteFriend() + "":\t"" + search); - overlayManager.forwardSearchOrCancel(source, new OSF2FSearchCancel(OSF2FMessage.CURRENT_VERSION, msg.getSearchID())); - } else { - search.gotResponse(); - // register the forwarding - logger.finest(""registering overlay forward: "" + searcher.getRemoteFriend().getNick() + ""<->"" + responder.getRemoteFriend().getNick()); - try { - responder.registerOverlayForward(msg, searcher, search.getSearch(), false); - searcher.registerOverlayForward(msg, responder, search.getSearch(), true); - } catch (FriendConnection.OverlayRegistrationError e) { - String direction = ""'"" + responder.getRemoteFriend().getNick() + ""'->'"" + searcher.getRemoteFriend().getNick() + ""'""; - e.direction = direction; - e.setupMessageSource = responder.getRemoteFriend().getNick(); - logger.warning(""not forwarding overlay setup request "" + direction + e.message); - debugChannelIdErrorSetupErrorStats.add(e); - return; - } - - // and send out the search - if (msg instanceof OSF2FHashSearchResp) { - searcher.sendChannelSetup((OSF2FHashSearchResp) msg.clone(), true); - } else if (msg instanceof OSF2FTextSearchResp) { - searcher.sendTextSearchResp((OSF2FTextSearchResp) msg.clone(), true); - } else { - Debug.out(""got unknown message: "" + msg.getDescription()); - } - } - } - - } - - /** - * - * @param source - * @param msg - * @return - */ - private boolean handleTextSearch(final FriendConnection source, final OSF2FTextSearch msg) { - - boolean shouldForward = true; - - if (logger.isLoggable(Level.FINER)) { - logger.finer(""handleTextSearch: "" + msg.getSearchString() + "" from "" + source.getRemoteFriend().getNick()); - } - - String searchString = msg.getSearchString(); - - // common case is no filtering. - if (filteredKeywords.length > 0) { - StringTokenizer toks = new StringTokenizer(searchString); - - for (String filter : filteredKeywords) { - if (searchString.contains(filter)) { - logger.fine(""Blocking search due to filter: "" + searchString + "" matched by: "" + filter); - return false; - } - } - } - - List results = filelistManager.handleSearch(source.getRemoteFriend(), searchString); - - if (results.size() > 0) { - if (canRespondToSearch()) { - logger.finer(""found matches: "" + results.size()); - // long fileListSize = results.getFileNum(); - - List delayedExecutionTasks = new LinkedList(); - long time = System.currentTimeMillis(); - for (FileCollection c : results) { - // send back a response - int channelId = random.nextInt(); - LinkedList list = new LinkedList(); - list.add(c); - byte[] encoded = FileListManager.encode_basic(new FileList(list), false); - - final OSF2FTextSearchResp resp = new OSF2FTextSearchResp(OSF2FMessage.CURRENT_VERSION, OSF2FMessage.FILE_LIST_TYPE_PARTIAL, msg.getSearchID(), channelId, encoded); - int delay = overlayManager.getSearchDelayForInfohash(source.getRemoteFriend(), c.getUniqueIdBytes()); - delayedExecutionTasks.add(new DelayedExecutionEntry(time + delay, 0, new TimerTask() { - @Override - public void run() { - /* - * check if the search got canceled while we were - * sleeping - */ - if (!isSearchCanceled(msg.getSearchID())) { - source.sendTextSearchResp(resp, false); - } - } - })); - } - delayedExecutor.queue(delayedExecutionTasks); - - } else { - // not enough capacity :-( - shouldForward = false; - } - } - - return shouldForward; - } - - public void sendDirectedHashSearch(FriendConnection target, byte[] infoHash) { - - long metainfohashhash = filelistManager.getInfoHashhash(infoHash); - - int newSearchId = 0; - while (newSearchId == 0) { - newSearchId = random.nextInt(); - } - OSF2FHashSearch search = new OSF2FHashSearch(OSF2FMessage.CURRENT_VERSION, newSearchId, metainfohashhash); - lock.lock(); - try { - sentSearches.put(newSearchId, new SentSearch(search)); - } finally { - lock.unlock(); - } - overlayManager.sendDirectedSearch(target, search); - - } - - public long getInfoHashHashFromSearchId(int searchId) { - lock.lock(); - try { - SentSearch sentSearch = sentSearches.get(searchId); - if (sentSearch != null && sentSearch.search instanceof OSF2FHashSearch) { - return ((OSF2FHashSearch) sentSearch.search).getInfohashhash(); - } - } finally { - lock.unlock(); - } - return -1; - } - - public void sendHashSearch(byte[] infoHash) { - long metainfohashhash = filelistManager.getInfoHashhash(infoHash); - - int newSearchId = 0; - while (newSearchId == 0) { - newSearchId = random.nextInt(); - } - OSF2FSearch search = new OSF2FHashSearch(OSF2FMessage.CURRENT_VERSION, newSearchId, metainfohashhash); - - // these should go in the slow (forward) path so to route around slow - // nodes - sendSearch(newSearchId, search, false); - } - - private void sendSearch(int newSearchId, OSF2FSearch search, boolean skipQueue) { - lock.lock(); - try { - sentSearches.put(newSearchId, new SentSearch(search)); - } finally { - lock.unlock(); - } - overlayManager.sendSearchOrCancel(search, skipQueue, false); - } - - public int sendTextSearch(String searchString, TextSearchListener listener) { - int newSearchId = 0; - while (newSearchId == 0) { - newSearchId = random.nextInt(); - } - - if (FileCollection.containsKeyword(searchString)) { - searchString = searchString.replaceAll("":"", "";""); - searchString = handleKeyWords(searchString); - } - - OSF2FSearch search = new OSF2FTextSearch(OSF2FMessage.CURRENT_VERSION, OSF2FMessage.FILE_LIST_TYPE_PARTIAL, newSearchId, searchString); - textSearchManager.sentSearch(newSearchId, searchString, listener); - sendSearch(newSearchId, search, false); - return newSearchId; - } - - private static String handleKeyWords(String searchString) { - searchString = FileCollection.removeWhiteSpaceAfteKeyChars(searchString); - String[] interestingKeyWords = new String[] { ""id"", ""sha1"", ""ed2k"" }; - int[] interestingKeyWordExectedKeyLen = { 20, 20, 16 }; - StringBuilder b = new StringBuilder(); - String[] split = searchString.split("" ""); - for (String s : split) { - // check for id - String toAdd = s; - for (int i = 0; i < interestingKeyWords.length; i++) { - String fromId = convertToBase64(s, interestingKeyWords[i], interestingKeyWordExectedKeyLen[i]); - if (fromId != null) { - toAdd = fromId; - } - } - b.append(toAdd + "" ""); - if (!toAdd.equals(s)) { - logger.fine(""converted search: "" + s + ""->"" + toAdd); - } - } - return b.toString().trim(); - } - - private static String convertToBase64(String searchTerm, String _keyword, int expectedBytes) { - for (String sep : FileCollection.KEYWORDENDINGS) { - String keyword = _keyword + sep; - if (searchTerm.contains(keyword)) { - logger.finer(""converting base: "" + searchTerm); - try { - String baseXHash = searchTerm.substring(keyword.length()); - logger.finer(""basex hash: "" + baseXHash); - String hash = ShareManagerTools.baseXtoBase64(baseXHash, expectedBytes); - String toAdd = keyword + hash; - logger.finer(""new string: "" + toAdd); - return toAdd; - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - return null; - } - - static class DebugChannelIdEntry implements Comparable { - final int count; - final String name; - - public DebugChannelIdEntry(String name, int count) { - super(); - this.name = name; - this.count = count; - } - - public int compareTo(DebugChannelIdEntry o) { - if (o.count > count) { - return 1; - } else if (o.count == count) { - return 0; - } else { - return -1; - } - } - } - - private static class DebugChannelSetupErrorStats { - private final LinkedList errorList = new LinkedList(); - - int MAX_SIZE = 10000; - - public void add(FriendConnection.OverlayRegistrationError error) { - lock.lock(); - try { - if (errorList.size() > MAX_SIZE) { - errorList.removeLast(); - } - errorList.addFirst(error); - } finally { - lock.unlock(); - } - } - - public String getDebugStats() { - StringBuilder b = new StringBuilder(); - HashMap errorsPerFriend = new HashMap(); - HashMap errorsPerPair = new HashMap(); - lock.lock(); - try { - - for (FriendConnection.OverlayRegistrationError error : errorList) { - final String s = error.setupMessageSource; - if (!errorsPerFriend.containsKey(s)) { - errorsPerFriend.put(s, 0); - } - errorsPerFriend.put(s, errorsPerFriend.get(s) + 1); - - String d = error.direction; - if (!errorsPerPair.containsKey(d)) { - errorsPerPair.put(d, 0); - } - errorsPerPair.put(d, errorsPerPair.get(d) + 1); - } - - ArrayList friendTotalOrder = new ArrayList(); - for (String f : errorsPerFriend.keySet()) { - friendTotalOrder.add(new DebugChannelIdEntry(f, errorsPerFriend.get(f))); - } - Collections.sort(friendTotalOrder); - b.append(""by source:\n""); - for (DebugChannelIdEntry e : friendTotalOrder) { - b.append("" "" + e.name + "" "" + e.count + ""\n""); - } - - ArrayList byPairOrder = new ArrayList(); - for (String f : errorsPerPair.keySet()) { - byPairOrder.add(new DebugChannelIdEntry(f, errorsPerPair.get(f))); - } - Collections.sort(byPairOrder); - b.append(""by pair:\n""); - for (DebugChannelIdEntry e : byPairOrder) { - b.append("" "" + e.name + "" "" + e.count + ""\n""); - } - - } finally { - lock.unlock(); - } - return b.toString(); - } - } - - class DelayedSearchQueue { - - long lastSearchesPerSecondLogTime = 0; - long lastBytesPerSecondCount = 0; - int searchCount = 0; - - private long mDelay; - private final LinkedBlockingQueue queue = new LinkedBlockingQueue(); - private final HashMap queuedSearches = new HashMap(); - - public DelayedSearchQueue(long delay) { - this.mDelay = delay; - Thread t = new Thread(new DelayedSearchQueueThread()); - t.setDaemon(true); - t.setName(SEARCH_QUEUE_THREAD_NAME); - t.start(); - } - - /** - * Warning -- changing this won't re-order things already in the queue, so if you add something with - * a much smaller delay than the current head of the queue, it will wait until that's removed before - * sending the new message. - */ - public void setDelay( long inDelay ) { - this.mDelay = inDelay; - } - - public void add(FriendConnection source, OSF2FSearch search) { - - if (lastSearchesPerSecondLogTime + 1000 < System.currentTimeMillis()) { - - lock.lock(); - try { - logger.fine(""Searches/sec: "" + searchCount + "" bytes: "" - + lastBytesPerSecondCount + "" searchQueueSize: "" - + queuedSearches.size()); - } finally { - lock.unlock(); - } - - lastSearchesPerSecondLogTime = System.currentTimeMillis(); - searchCount = 0; - lastBytesPerSecondCount = 0; - } - - searchCount++; - lastBytesPerSecondCount += FriendConnectionQueue.getMessageLen(search); - - lock.lock(); - try { - - // Flush the accounting info every 60 seconds - if (SearchManager.this.lastSearchAccountingFlush + 60*1000 < System.currentTimeMillis()) { - lastSearchAccountingFlush = System.currentTimeMillis(); - searchesPerFriend.clear(); - } - - // If the search queue is more than half full, start dropping searches - // proportional to how much of the total queue each person is - // consuming - if (queuedSearches.size() > 0.25 * MAX_SEARCH_QUEUE_LENGTH) { - if (searchesPerFriend.containsKey(source.getRemoteFriend())) { - int outstanding = searchesPerFriend.get(source.getRemoteFriend()).v; - - // We add a hard limit on the number of searches from any one person. - if (outstanding > 0.15 * MAX_SEARCH_QUEUE_LENGTH) { - logger.fine(""Dropping due to 25% of total queue consumption "" + source.getRemoteFriend().getNick() + "" "" + outstanding + "" / "" + MAX_SEARCH_QUEUE_LENGTH); - return; - } - - // In other cases, we drop proportional to the consumption of the overall queue. - double acceptProb = (double) outstanding / (double) queuedSearches.size(); - if (random.nextDouble() < acceptProb) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(""*** RED for search from "" + source + "" outstanding: "" - + outstanding + "" total: "" + queuedSearches.size()); - } - return; - } - } - } - - if (queuedSearches.size() > MAX_SEARCH_QUEUE_LENGTH) { - if (logger.isLoggable(Level.FINER)) { - logger.finer(""not forwarding search, queue length too large. id: "" - + search.getSearchID()); - } - return; - } - if (!queuedSearches.containsKey(search.getSearchID())) { - logger.finest(""adding search to forward queue, will forward in "" + mDelay - + "" ms""); - DelayedSearchQueueEntry entry = new DelayedSearchQueueEntry(search, source, - System.currentTimeMillis() + mDelay); - - if (searchesPerFriend.containsKey(source.getRemoteFriend()) == false) { - searchesPerFriend.put(source.getRemoteFriend(), new SearchManager.MutableInteger()); - } - searchesPerFriend.get(source.getRemoteFriend()).v++; - logger.finest(""Search for friend: "" + source.getRemoteFriend().getNick() + "" "" - + searchesPerFriend.get(source.getRemoteFriend()).v); - - queuedSearches.put(search.getSearchID(), entry); - queue.add(entry); - - } else { - logger.finer(""search already in queue, not adding""); - } - } finally { - lock.unlock(); - } - } - - /* - * make sure to already have the lock when calling this - */ - public boolean isQueued(OSF2FSearch search) { - return queuedSearches.containsKey(search.getSearchID()); - } - - class DelayedSearchQueueThread implements Runnable { - - public void run() { - while (true) { - try { - DelayedSearchQueueEntry e = queue.take(); - long timeUntilSend = e.dontSendBefore - System.currentTimeMillis(); - if (timeUntilSend > 0) { - logger.finer(""got search ("" + e.search.getDescription() + "") to forward, waiting "" + timeUntilSend + "" ms until sending""); - Thread.sleep(timeUntilSend); - } - forwardSearch(e.source, e.search); - /* - * remove the search from the queuedSearchesMap - */ - lock.lock(); - try { - queuedSearches.remove(e.search.getSearchID()); - // If searchesPerFriend was flushed while this search was in the - // queue, the get() call will return null. - if (searchesPerFriend.containsKey(e.source.getRemoteFriend())) { - searchesPerFriend.get(e.source.getRemoteFriend()).v--; - } - } finally { - lock.unlock(); - } - /* - * if we didn't sleep at all, sleep the min time between - * searches - */ - if (timeUntilSend < 1) { - double ms = 1000.0 / FriendConnection.MAX_OUTGOING_SEARCH_RATE; - int msFloor = (int) Math.floor(ms); - int nanosLeft = (int) Math.round((ms - msFloor) * 1000000.0); - logger.finest(""sleeping "" + msFloor + ""ms + "" + nanosLeft + "" ns""); - Thread.sleep(msFloor, Math.min(999999, nanosLeft)); - } - - } catch (Exception e1) { - logger.warning(""*** Delayed search queue thread error: "" + e1.toString()); - e1.printStackTrace(); - BackendErrorLog.get().logException(e1); - } - } - } - } - } - - static class DelayedSearchQueueEntry { - final long dontSendBefore; - final OSF2FSearch search; - final FriendConnection source; - final long insertionTime; - - public DelayedSearchQueueEntry(OSF2FSearch search, FriendConnection source, long dontSendBefore) { - this.insertionTime = System.currentTimeMillis(); - this.search = search; - this.source = source; - this.dontSendBefore = dontSendBefore; - } - } - - class ForwardedSearch { - private int responsesForwarded = 0; - private final OSF2FSearch search; - private final FriendConnection source; - private final long time; - - public ForwardedSearch(FriendConnection source, OSF2FSearch search) { - this.time = System.currentTimeMillis(); - this.source = source; - this.search = search; - - } - - public long getAge() { - return System.currentTimeMillis() - this.time; - } - - public int getResponseNum() { - return responsesForwarded; - } - - public OSF2FSearch getSearch() { - return search; - } - - public int getSearchId() { - return search.getSearchID(); - } - - public FriendConnection getSource() { - return source; - } - - public void gotResponse() { - responsesForwarded++; - } - - public boolean isTimedOut() { - return getAge() > MAX_SEARCH_AGE; - } - } - - static class RotatingBloomFilter { - private static final int OBJECTS_TO_STORE = 1000000; - - private static final int SIZE_IN_BITS = 10240 * 1024; - - private long currentFilterCreated; - private final LinkedList filters = new LinkedList(); - private final int maxBuckets; - private final long maxFilterAge; - - public RotatingBloomFilter(long totalAge, int buckets) { - this.maxBuckets = buckets; - this.maxFilterAge = (totalAge / buckets) + 1; - rotate(); - } - - public boolean contains(int searchId, int searchValue) { - byte[] bytes = bytesFromInts(searchId, searchValue); - for (BloomFilter f : filters) { - if (f.test(bytes)) { - return true; - } - } - - return false; - } - - public double getPrevFilterFalsePositiveEst() { - if (filters.size() > 1) { - return filters.get(1).getPredictedFalsePositiveRate(); - } else { - return filters.getFirst().getPredictedFalsePositiveRate(); - } - } - - public int getPrevFilterNumElements() { - if (filters.size() > 1) { - return filters.get(1).getUniqueObjectsStored(); - } else { - return filters.getFirst().getUniqueObjectsStored(); - } - } - - public void insert(int searchId, int searchValue) { - byte[] bytes = bytesFromInts(searchId, searchValue); - filters.getFirst().insert(bytes); - } - - private void rotate() { - - if (filters.size() > 0) { - BloomFilter prevFilter = filters.getFirst(); - String str = ""Rotating bloom filter: objects="" + prevFilter.getUniqueObjectsStored() + "" predicted false positive rate="" + (100 * prevFilter.getPredictedFalsePositiveRate() + ""%""); - logger.info(str); - } - currentFilterCreated = System.currentTimeMillis(); - try { - filters.addFirst(new BloomFilter(SIZE_IN_BITS, OBJECTS_TO_STORE)); - } catch (NoSuchAlgorithmException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - if (filters.size() > maxBuckets) { - filters.removeLast(); - } - } - - public boolean rotateIfNeeded() { - long currentFilterAge = System.currentTimeMillis() - currentFilterCreated; - if (currentFilterAge > maxFilterAge) { - rotate(); - return true; - } - return false; - } - - private static byte[] bytesFromInts(int int1, int int2) { - byte[] bytes = new byte[8]; - - bytes[0] = (byte) (int1 >>> 24); - bytes[1] = (byte) (int1 >>> 16); - bytes[2] = (byte) (int1 >>> 8); - bytes[3] = (byte) int1; - - bytes[4] = (byte) (int2 >>> 24); - bytes[5] = (byte) (int2 >>> 16); - bytes[6] = (byte) (int2 >>> 8); - bytes[7] = (byte) int2; - return bytes; - } - - public static void main(String[] args) { - OSF2FMain.getSingelton(); - logger.setLevel(Level.FINE); - Random rand = new Random(); - - RotatingBloomFilter bf = new RotatingBloomFilter(60 * 1000, 4); - - Set inserts = new HashSet(); - for (int j = 0; j < 8; j++) { - for (int i = 0; i < 20000; i++) { - int r1 = rand.nextInt(); - int r2 = rand.nextInt(); - byte[] bytes = bytesFromInts(r1, r2); - inserts.add(new String(Base64.encode(bytes))); - bf.insert(r1, r2); - if (!bf.contains(r1, r2)) { - System.err.println(""insert failes (does not contain it anymore)""); - } - } - bf.rotate(); - } - - int fps = 0, to_check = 200000; - for (int i = 0; i < to_check; i++) { - int int1; - int int2; - byte[] bytes; - do { - int1 = rand.nextInt(); - int2 = rand.nextInt(); - bytes = bytesFromInts(int1, int2); - } while (inserts.contains(new String(Base64.encode(bytes))) == true); - if (bf.contains(int1, int2) == true) - fps++; - } - - System.out.println(""false positive check, "" + fps + ""/"" + to_check); - - System.out.println(""mem: "" + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); - - } - - } - - class SentSearch { - private int responses = 0; - private final OSF2FSearch search; - - private final long time; - - public SentSearch(OSF2FSearch search) { - this.search = search; - this.time = System.currentTimeMillis(); - } - - public long getAge() { - return System.currentTimeMillis() - this.time; - } - - public int getResponseNum() { - return responses; - } - - public OSF2FSearch getSearch() { - return search; - } - - public void gotResponse() { - responses++; - } - - public boolean isTimedOut() { - return getAge() > MAX_SEARCH_AGE; - } - - } - - public interface TextSearchListener { - public void searchResponseReceived(TextSearchResponseItem r); - } - - class TextSearchManager { - private final ConcurrentHashMap responses; - private final ConcurrentHashMap listeners; - - public TextSearchManager() { - responses = new ConcurrentHashMap(); - listeners = new ConcurrentHashMap(); - } - - public List getResults(int searchId) { - TextSearchResponse resps = responses.get(searchId); - - HashMap result = new HashMap(); - - if (resps != null) { - /* - * group into file collections - */ - for (TextSearchResponseItem item : resps.getItems()) { - for (FileCollection collection : item.getFileList().getElements()) { - if (result.containsKey(collection.getUniqueID())) { - TextSearchResult existing = result.get(collection.getUniqueID()); - existing.merge(item, collection); - } else { - // mark stuff that we already have - boolean alreadyInLibrary = true; - GlobalManager globalManager = AzureusCoreImpl.getSingleton().getGlobalManager(); - DownloadManager dm = globalManager.getDownloadManager(new HashWrapper(collection.getUniqueIdBytes())); - if (dm == null) { - alreadyInLibrary = false; - } - result.put(collection.getUniqueID(), new TextSearchResult(item, collection, alreadyInLibrary)); - } - } - } - - // /* - // * verify that we didn't get any bad data - // */ - // for (TextSearchResult item : result.values()) { - // FileCollection collection = item.getCollection(); - // String searchString = resps.getSearchString(); - // boolean collectionMatch = collection.nameMatch(searchString); - // - // Set filteredFiles = new - // HashSet(); - // List allChildren = collection.getChildren(); - // for (int i = 0; i < allChildren.size(); i++) { - // FileListFile f = allChildren.get(i); - // if (filteredFiles.contains(f)) { - // continue; - // } - // if (collectionMatch) { - // filteredFiles.add(f); - // } else if (f.searchMatch(searchString)) { - // filteredFiles.add(f); - // } else { - // logger.fine(""got search result that doesn't match search: "" + - // f.getFileName() + "" ! "" + searchString); - // } - // } - // logger.fine(collection.getName() + "" totalResp: "" + - // allChildren.size() + "" afterFiler="" + filteredFiles.size()); - // collection.setChildren(new - // ArrayList(filteredFiles)); - // } - - return new ArrayList(result.values()); - } - logger.fine(""no responses for searchId="" + searchId); - return new ArrayList(); - } - - public void gotSearchResponse(int searchId, Friend throughFriend, FileList fileList, int channelId, int connectionId) { - TextSearchResponse r = responses.get(searchId); - if (r != null) { - long age = System.currentTimeMillis() - r.getTime(); - TextSearchResponseItem item = new TextSearchResponseItem(throughFriend, fileList, age, channelId, connectionId); - r.add(item); - TextSearchListener listener = listeners.get(searchId); - if (listener != null) { - listener.searchResponseReceived(item); - } - } else { - logger.warning(""got response for unknown search""); - } - } - - public void sentSearch(int searchId, String searchString, TextSearchListener listener) { - responses.put(searchId, new TextSearchResponse(searchString)); - if (listener != null) { - listeners.put(searchId, listener); - } - } - - public void clearOldResponses() { - for (Iterator iterator = responses.keySet().iterator(); iterator.hasNext();) { - Integer key = iterator.next(); - TextSearchResponse response = responses.get(key); - if (System.currentTimeMillis() - response.getTime() > 10 * 60 * 1000) { - iterator.remove(); - listeners.remove(key); - } - - } - } - } - - public boolean isSearchInBloomFilter(OSF2FSearch search) { - lock.lock(); - try { - int searchID = search.getSearchID(); - int valueID = search.getValueID(); - if (recentSearches.contains(searchID, valueID)) { - bloomSearchesBlockedCurr++; - } - } finally { - lock.unlock(); - } - return false; - } + public static final String SEARCH_QUEUE_THREAD_NAME = ""DelayedSearchQueue""; + + private final static BigFatLock lock = OverlayManager.lock; + private static Logger logger = Logger.getLogger(SearchManager.class.getName()); + // search sources are remembered for 1 minute, any replies after this will + // be dropped + public static final long MAX_SEARCH_AGE = 60 * 1000; + public static final int MAX_SEARCH_QUEUE_LENGTH = 100; + // private static final int MAX_SEARCH_RESP_BEFORE_CANCEL = + // COConfigurationManager.getIntParameter(""f2f_search_max_paths""); + + protected int mMaxSearchResponsesBeforeCancel = COConfigurationManager + .getIntParameter(""f2f_search_max_paths""); + + // don't respond if average torrent upload rate is less than 10K/s + private static final double NO_RESPONSE_TORRENT_AVERAGE_RATE = 10000; + + private static final double NO_RESPONSE_TOTAL_FRAC_OF_MAX_UPLOAD = 0.9; + + private static final double NO_RESPONSE_TRANSPORT_FRAC_OF_MAX_UPLOAD = 0.75; + /* + * this is to avoid searches living forever, search uid are remembered for + * 45min-1h, there are 4 bloom filter buckets that are rotating, each one + * containing 15minutes worth of searches + */ + private static final int RECENT_SEARCH_BUCKETS = 4; + + private static final long RECENT_SEARCH_MEMORY = 20 * 60 * 1000; + // static final int SEARCH_DELAY = + // COConfigurationManager.getIntParameter(""f2f_search_forward_delay""); + protected int mSearchDelay = COConfigurationManager.getIntParameter(""f2f_search_forward_delay""); + + /** + * This Map is protected by the BigFatLock: lock. We use this to drop + * searches from friends that are crowding the outgoing search queue early, + * thus allowing friends that send searches more rarely to get through. + * + * This map is emptied once every 60 seconds to deal with accounting errors + * that may accumulate. + */ + class MutableInteger { + public int v = 0; + } + + long lastSearchAccountingFlush = System.currentTimeMillis(); + private final Map searchesPerFriend = new HashMap(); + + private int bloomSearchesBlockedCurr = 0; + + private int bloomSearchesBlockedPrev = 0; + private int bloomSearchesSentCurr = 0; + private int bloomSearchesSentPrev = 0; + + private final HashMap canceledSearches; + private final DebugChannelSetupErrorStats debugChannelIdErrorSetupErrorStats = new DebugChannelSetupErrorStats(); + + private final DelayedSearchQueue delayedSearchQueue; + + // private final DeterministicDelayResponseQueue delayedResponseQueue; + + private final FileListManager filelistManager; + + private final HashMap forwardedSearches; + private int forwardedSearchNum = 0; + private List hashSearchStats = new LinkedList(); + + private boolean includeLanUploads; + private final double NO_FORWARD_FRAC_OF_MAX_UPLOAD = 0.9; + private final OverlayManager overlayManager; + + private final Random random = new Random(); + private final RandomnessManager randomnessManager; + + private int rateLimitInKBps; + + private final RotatingBloomFilter recentSearches; + private final HashMap sentSearches; + private final GlobalManagerStats stats; + private final TextSearchManager textSearchManager; + + private List textSearchStats = new LinkedList(); + + private final DelayedExecutor delayedExecutor; + + private String[] filteredKeywords = new String[0]; + + public SearchManager(OverlayManager overlayManager, FileListManager filelistManager, + RandomnessManager randomnessManager, GlobalManagerStats stats) { + this.stats = stats; + this.delayedExecutor = DelayedExecutorService.getInstance().getVariableDelayExecutor(); + // this.delayedResponseQueue = new DeterministicDelayResponseQueue(); + this.overlayManager = overlayManager; + this.sentSearches = new HashMap(); + this.forwardedSearches = new HashMap(); + this.canceledSearches = new HashMap(); + this.filelistManager = filelistManager; + this.randomnessManager = randomnessManager; + this.textSearchManager = new TextSearchManager(); + this.recentSearches = new RotatingBloomFilter(RECENT_SEARCH_MEMORY, RECENT_SEARCH_BUCKETS); + this.delayedSearchQueue = new DelayedSearchQueue(mSearchDelay); + COConfigurationManager.addAndFireParameterListeners(new String[] { ""LAN Speed Enabled"", + ""Max Upload Speed KBs"", ""oneswarm.search.filter.keywords"", ""f2f_search_max_paths"", + ""f2f_search_forward_delay"" }, new ParameterListener() { + public void parameterChanged(String parameterName) { + includeLanUploads = !COConfigurationManager + .getBooleanParameter(""LAN Speed Enabled""); + rateLimitInKBps = COConfigurationManager.getIntParameter(""Max Upload Speed KBs""); + + StringList keywords = COConfigurationManager + .getStringListParameter(""oneswarm.search.filter.keywords""); + if (keywords != null) { + String[] neu = new String[keywords.size()]; + for (int i = 0; i < keywords.size(); i++) { + String firstTok = (new StringTokenizer(keywords.get(i))).nextToken(); + neu[i] = firstTok; + } + filteredKeywords = neu; + logger.fine(""Updated filtered keywords "" + keywords.size()); + } + + mMaxSearchResponsesBeforeCancel = COConfigurationManager + .getIntParameter(""f2f_search_max_paths""); + + mSearchDelay = COConfigurationManager.getIntParameter(""f2f_search_forward_delay""); + delayedSearchQueue.setDelay(mSearchDelay); + } + }); + } + + private boolean canForwardSearch() { + double util = fracUpload(); + if (util == -1 || util < NO_FORWARD_FRAC_OF_MAX_UPLOAD) { + return true; + } else { + logger.finest(""not forwarding search (overloaded, util="" + util + "")""); + return false; + } + } + + private boolean canRespondToSearch() { + double totalUtil = fracUpload(); + if (totalUtil == -1) { + return true; + } + // ok, check if we are using more than 90% of total + if (totalUtil < NO_RESPONSE_TOTAL_FRAC_OF_MAX_UPLOAD) { + return true; + } + double transUtil = fracTransportUpload(); + // check if we are using more than 75% for transports + if (transUtil < NO_RESPONSE_TRANSPORT_FRAC_OF_MAX_UPLOAD) { + return true; + } + + double torrentAvgSpeed = getAverageUploadPerRunningTorrent(); + if (torrentAvgSpeed == -1) { + return true; + } + if (torrentAvgSpeed > NO_RESPONSE_TORRENT_AVERAGE_RATE) { + return true; + } + if (logger.isLoggable(Level.FINER)) { + logger.finer(""not responding to search (overloaded, util="" + transUtil + "")""); + } + return false; + } + + public void clearTimedOutSearches() { + lock.lock(); + try { + /* + * check if we need to rotate the bloom filter of recent searches + */ + boolean rotated = recentSearches.rotateIfNeeded(); + if (rotated) { + bloomSearchesBlockedPrev = bloomSearchesBlockedCurr; + bloomSearchesBlockedCurr = 0; + bloomSearchesSentPrev = bloomSearchesSentCurr; + bloomSearchesSentCurr = 0; + } + + for (Iterator iterator = forwardedSearches.values().iterator(); iterator + .hasNext();) { + ForwardedSearch fs = iterator.next(); + if (fs.isTimedOut()) { + iterator.remove(); + } + } + + for (Iterator iterator = sentSearches.values().iterator(); iterator + .hasNext();) { + SentSearch sentSearch = iterator.next(); + if (sentSearch.isTimedOut()) { + iterator.remove(); + if (sentSearch.getSearch() instanceof OSF2FHashSearch) { + hashSearchStats.add(sentSearch.getResponseNum()); + } else if (sentSearch.getSearch() instanceof OSF2FTextSearch) { + textSearchStats.add(sentSearch.getResponseNum()); + } + } + } + + /* + * Delete any expired canceled searches + */ + LinkedList toDelete = new LinkedList(); + for (Integer key : canceledSearches.keySet()) { + long age = System.currentTimeMillis() - canceledSearches.get(key); + if (age > MAX_SEARCH_AGE) { + toDelete.add(key); + } + } + + for (Integer key : toDelete) { + canceledSearches.remove(key); + } + + textSearchManager.clearOldResponses(); + } finally { + lock.unlock(); + } + } + + public List debugCanceledSearches() { + List l = new LinkedList(); + lock.lock(); + try { + for (Integer s : canceledSearches.keySet()) { + l.add(""search="" + Integer.toHexString(s) + "" age="" + + ((System.currentTimeMillis() - canceledSearches.get(s)) / 1000) + ""s""); + } + } finally { + lock.unlock(); + } + return l; + } + + public List debugForwardedSearches() { + List l = new LinkedList(); + lock.lock(); + try { + for (ForwardedSearch f : forwardedSearches.values()) { + l.add(""search="" + Integer.toHexString(f.getSearchId()) + "" responses="" + + f.getResponseNum() + "" age="" + (f.getAge() / 1000) + ""s""); + } + } finally { + lock.unlock(); + } + return l; + } + + public List debugSentSearches() { + List l = new LinkedList(); + lock.lock(); + try { + for (SentSearch s : sentSearches.values()) { + l.add(""search="" + Integer.toHexString(s.getSearch().getSearchID()) + "" responses="" + + s.getResponseNum() + "" age="" + (s.getAge() / 1000) + ""s""); + } + } finally { + lock.unlock(); + } + return l; + } + + private void forwardSearch(FriendConnection source, OSF2FSearch search) { + lock.lock(); + try { + + // check if search is canceled or forwarded first + int searchID = search.getSearchID(); + if (forwardedSearches.containsKey(searchID)) { + logger.finest(""not forwarding search, already forwarded. id: "" + searchID); + return; + } + + if (canceledSearches.containsKey(searchID)) { + logger.finest(""not forwarding search, cancel received. id: "" + searchID); + return; + } + + int valueID = search.getValueID(); + if (recentSearches.contains(searchID, valueID)) { + bloomSearchesBlockedCurr++; + logger.finest(""not forwarding search, in recent filter. id: "" + searchID); + return; + } + bloomSearchesSentCurr++; + forwardedSearchNum++; + if (logger.isLoggable(Level.FINEST)) { + logger.finest(""forwarding search "" + search.getDescription() + "" id: "" + searchID); + } + forwardedSearches.put(searchID, new ForwardedSearch(source, search)); + recentSearches.insert(searchID, valueID); + } finally { + lock.unlock(); + } + + overlayManager.forwardSearchOrCancel(source, search.clone()); + } + + private double fracTransportUpload() { + + if (rateLimitInKBps < 1) { + return -1; + } + long uploadRate = overlayManager.getTransportSendRate(includeLanUploads); + + double util = uploadRate / (rateLimitInKBps * 1024.0); + return util; + } + + private double fracUpload() { + + if (rateLimitInKBps < 1) { + return -1; + } + long uploadRate; + if (!includeLanUploads) { + uploadRate = stats.getProtocolSendRateNoLAN() + stats.getDataSendRateNoLAN(); + } else { + uploadRate = stats.getProtocolSendRate() + stats.getDataSendRate(); + } + + double util = uploadRate / (rateLimitInKBps * 1024.0); + return util; + } + + public int getAndClearForwardedSearchNum() { + lock.lock(); + try { + int ret = forwardedSearchNum; + forwardedSearchNum = 0; + return ret; + } finally { + lock.unlock(); + } + } + + public List getAndClearHashSearchStats() { + lock.lock(); + try { + List ret = hashSearchStats; + hashSearchStats = new LinkedList(); + return ret; + } finally { + lock.unlock(); + } + } + + public List getAndClearTextSearchStats() { + lock.lock(); + try { + List ret = textSearchStats; + textSearchStats = new LinkedList(); + return ret; + } finally { + lock.unlock(); + } + } + + @SuppressWarnings(""unchecked"") + private double getAverageUploadPerRunningTorrent() { + LinkedList dms = new LinkedList(); + final List downloadManagers = AzureusCoreImpl.getSingleton() + .getGlobalManager().getDownloadManagers(); + dms.addAll(downloadManagers); + + long total = 0; + int num = 0; + + for (DownloadManager dm : dms) { + final DownloadManagerStats s = dm.getStats(); + if (s == null) { + continue; + } + final PEPeerManager p = dm.getPeerManager(); + if (p == null) { + continue; + } + + if (p.getNbPeers() == 0 && p.getNbSeeds() == 0) { + continue; + } + + long uploadRate = s.getDataSendRate() + s.getProtocolSendRate(); + total += uploadRate; + num++; + } + if (num == 0) { + return -1; + } + + return ((double) total) / num; + + } + + public String getSearchDebug() { + StringBuilder b = new StringBuilder(); + b.append(""total_frac="" + fracUpload() + ""\ntransport_frac="" + fracTransportUpload() + + ""\ntorrent_avg="" + getAverageUploadPerRunningTorrent()); + b.append(""\ncan forward="" + canForwardSearch()); + b.append(""\ncan respond="" + canRespondToSearch()); + + b.append(""\n\nforwarded searches size="" + forwardedSearches.size() + "" canceled size="" + + canceledSearches.size() + "" sent size="" + sentSearches.size()); + b.append(""\nbloom: stored="" + recentSearches.getPrevFilterNumElements() + + "" est false positives="" + + (100 * recentSearches.getPrevFilterFalsePositiveEst() + ""%"")); + b.append(""\nbloom blocked|sent curr="" + bloomSearchesBlockedCurr + ""|"" + + bloomSearchesSentCurr + "" prev="" + bloomSearchesBlockedPrev + ""|"" + + bloomSearchesSentPrev); + b.append(""\n\n"" + debugChannelIdErrorSetupErrorStats.getDebugStats()); + + long sum = 0, now = System.currentTimeMillis(), count = 0; + + // Include per-friend queue stats + lock.lock(); + try { + Map counts = new HashMap(); + for (DelayedSearchQueueEntry e : delayedSearchQueue.queuedSearches.values()) { + + count++; + sum += (now - e.insertionTime); + + String nick = e.source.getRemoteFriend().getNick(); + if (counts.containsKey(nick) == false) { + counts.put(nick, new MutableInteger()); + } + counts.get(nick).v++; + } + for (String nick : counts.keySet()) { + b.append(""\n\t"" + nick + "" -> "" + counts.get(nick).v); + } + b.append(""\n\nQueue size: "" + delayedSearchQueue.queuedSearches.size()); + } finally { + lock.unlock(); + } + + b.append(""\nAverage queued search delay: "" + (double) sum / (double) count); + + return b.toString(); + } + + public List getSearchResult(int searchId) { + return textSearchManager.getResults(searchId); + } + + private boolean handleHashSearch(final FriendConnection source, final OSF2FHashSearch msg) { + + // we might actually have this data + final byte[] infohash = filelistManager.getMetainfoHash(msg.getInfohashhash()); + + // Check if this is a service + SharedService service = ServiceSharingManager.getInstance().handleSearch(msg); + if (service != null) { + try { + // TODO: support artificial delays and merge with normal search + // handling code + final int newChannelId = random.nextInt(); + final int transportFakePathId = random.nextInt(); + final int pathID = randomnessManager.getDeterministicRandomInt((int) msg + .getInfohashhash()); + final OSF2FHashSearchResp response = new OSF2FHashSearchResp( + OSF2FMessage.CURRENT_VERSION, msg.getSearchID(), newChannelId, pathID); + + ServiceConnection conn = new ServiceConnection(service, source, newChannelId, + transportFakePathId, true); + // register it with the friendConnection + source.registerOverlayTransport(conn); + // send the channel setup message + source.sendChannelSetup(response, false); + } catch (OverlayRegistrationError e) { + Debug.out(""got an error when registering incoming transport to '"" + + source.getRemoteFriend().getNick() + ""': "" + e.message); + } + return false; + } else if (infohash != null) { + DownloadManager dm = AzureusCoreImpl.getSingleton().getGlobalManager() + .getDownloadManager(new HashWrapper(infohash)); + + if (dm != null) { + logger.fine(""found match: "" + new String(Base64.encode(infohash))); + + // check if the torrent allow osf2f search peers + boolean allowed = OverlayTransport.checkOSF2FAllowed(dm.getDownloadState() + .getPeerSources(), dm.getDownloadState().getNetworks()); + if (!allowed) { + logger.warning(""got search match for torrent "" + + ""that does not allow osf2f peers""); + return true; + } + + boolean completedOrDownloading = FileListManager.completedOrDownloading(dm); + if (!completedOrDownloading) { + return true; + } + + // check if we have the capacity to respond + if (canRespondToSearch() == false) { + return false; + } + + // yeah, we actually have this stuff and we have spare capacity + // create an overlay transport + final int newChannelId = random.nextInt(); + final int transportFakePathId = random.nextInt(); + // set the path id for the overlay transport for something + // random (since otherwise all transports for this infohash will + // get the same pathid, which will limit it to be only one. The + // path id set in the channel setup message will be + // deterministic. It is the responsibility of the source to + // monitor for duplicate paths + + // set the path id to something that will persist between + // searches, for example a deterministic random seeded with + // the infohashhash + final int pathID = randomnessManager.getDeterministicRandomInt((int) msg + .getInfohashhash()); + + // get the delay for this overlaytranport, that is the latency + // component of the delay + final int overlayDelay = overlayManager.getLatencyDelayForInfohash( + source.getRemoteFriend(), infohash); + + TimerTask task = new TimerTask() { + @Override + public void run() { + try { + /* + * check if the search got canceled while we were + * sleeping + */ + if (!isSearchCanceled(msg.getSearchID())) { + final OSF2FHashSearchResp response = new OSF2FHashSearchResp( + OSF2FMessage.CURRENT_VERSION, msg.getSearchID(), + newChannelId, pathID); + + final OverlayTransport transp = new OverlayTransport(source, + newChannelId, infohash, transportFakePathId, false, + overlayDelay); + // register it with the friendConnection + source.registerOverlayTransport(transp); + // send the channel setup message + source.sendChannelSetup(response, false); + } + } catch (OverlayRegistrationError e) { + Debug.out(""got an error when registering incoming transport to '"" + + source.getRemoteFriend().getNick() + ""': "" + e.message); + } + } + + }; + delayedExecutor.queue(overlayDelay, task); + + // we are still forwarding if there are files in the torrent + // that we chose not to download + DiskManagerFileInfo[] diskManagerFileInfo = dm.getDiskManagerFileInfo(); + for (DiskManagerFileInfo d : diskManagerFileInfo) { + if (d.isSkipped()) { + return true; + } + } + /* + * ok, we shouldn't forward this, already sent a hash response + * and we have/are downloading all the files + */ + return false; + } + } + + return true; + } + + private boolean isSearchCanceled(int searchId) { + boolean canceled = false; + lock.lock(); + try { + if (canceledSearches.containsKey(searchId)) { + canceled = true; + } + } finally { + lock.unlock(); + } + return canceled; + } + + /** + * Returns the probability of rejecting a search from this friend given the + * share of the overall queue + */ + public double getFriendSearchDropProbability(Friend inFriend) { + + lock.lock(); + try { + + // Always accept if we don't have any searches from friend. + if (searchesPerFriend.get(inFriend) == null) { + return 0; + } + + // Reject proportionally to recent rate. Do not admit more than + // X/sec. + // Also, proportional to processing queue size. + double rateBound = delayedSearchQueue.searchCount / 80.0; + double queueBound = (double) delayedSearchQueue.queuedSearches.size() + / (double) MAX_SEARCH_QUEUE_LENGTH; + + return Math.max(rateBound, queueBound); + + } finally { + lock.unlock(); + } + } + + private void handleIncomingHashSearchResponse(OSF2FHashSearch hashSearch, + FriendConnection source, OSF2FHashSearchResp msg) { + // great, we found someone that has what we searched for! + // create the overlay transport + byte[] infoHash = filelistManager.getMetainfoHash(hashSearch.getInfohashhash()); + if (infoHash == null) { + logger.warning(""got channel setup request, "" + ""but the infohash we searched for "" + + ""is not in filelistmananger""); + return; + } + + DownloadManager dm = AzureusCoreImpl.getSingleton().getGlobalManager() + .getDownloadManager(new HashWrapper(infoHash)); + if (dm == null) { + logger.warning(""got channel setup request, "" + ""but the downloadmanager is null""); + return; + } + + if (source.hasRegisteredPath(msg.getPathID())) { + logger.finer(""got channel setup response, "" + + ""but path is already used: sending back a reset""); + source.sendChannelRst(new OSF2FChannelReset(OSF2FMessage.CURRENT_VERSION, msg + .getChannelID())); + return; + } + + OverlayTransport overlayTransport = new OverlayTransport(source, msg.getChannelID(), + infoHash, msg.getPathID(), true, overlayManager.getLatencyDelayForInfohash( + source.getRemoteFriend(), infoHash)); + // register it with the friendConnection + try { + source.registerOverlayTransport(overlayTransport); + // safe to start it since we know that the other party is interested + overlayTransport.start(); + } catch (OverlayRegistrationError e) { + Debug.out(""got an error when registering outgoing transport: "" + e.message); + return; + } + + } + + public void handleIncomingSearch(FriendConnection source, OSF2FSearch msg) { + lock.lock(); + try { + logger.finest(""got search: "" + msg.getDescription()); + // first, check if we either sent or forwarded this search before + if (forwardedSearches.containsKey(msg.getSearchID()) + || sentSearches.containsKey(msg.getSearchID()) + || delayedSearchQueue.isQueued(msg)) { + return; + } + } finally { + lock.unlock(); + } + + boolean shouldForward = true; + // second, check if we actually can do something about this + if (msg instanceof OSF2FHashSearch) { + shouldForward = handleHashSearch(source, (OSF2FHashSearch) msg); + } else if (msg instanceof OSF2FTextSearch) { + shouldForward = handleTextSearch(source, (OSF2FTextSearch) msg); + } else { + logger.warning(""received unrecgonized search type: "" + msg.getID() + "" / "" + + msg.getClass().getCanonicalName()); + } + + /* + * check if we are at full capacity + */ + if (canForwardSearch() == false) { + shouldForward = false; + } + + if (shouldForward) { + // ok, seems like we should attempt to forward this, put it in + // the queue + delayedSearchQueue.add(source, msg); + } + + } + + public void handleIncomingSearchCancel(FriendConnection source, OSF2FSearchCancel msg) { + + boolean forward = false; + lock.lock(); + try { + + /* + * if this is the first time we see the cancel, check if we + * forwarded this search, if we did, send a cancel + */ + if (!canceledSearches.containsKey(msg.getSearchID())) { + canceledSearches.put(msg.getSearchID(), System.currentTimeMillis()); + /* + * we only forward the cancel if we already sent the search + */ + if (forwardedSearches.containsKey(msg.getSearchID())) { + forward = true; + } else { + logger.fine(""got search cancel for unknown search id""); + } + } + } finally { + lock.unlock(); + } + if (forward) { + overlayManager.forwardSearchOrCancel(source, msg); + } + } + + /** + * There are 2 possible explanations for getting a search response, either + * we got a response for a search we sent ourselves, or we got a response + * for a search we forwarded + * + * @param source + * connection from where we got the setup + * @param msg + * the channel setup message + */ + public void handleIncomingSearchResponse(FriendConnection source, OSF2FSearchResp msg) { + SentSearch sentSearch; + lock.lock(); + try { + sentSearch = sentSearches.get(msg.getSearchID()); + } finally { + lock.unlock(); + } + // first, if might be a search we sent + if (sentSearch != null) { + logger.finest(""got response to search: "" + sentSearch.getSearch().getDescription()); + OSF2FSearch search = sentSearch.getSearch(); + // update response stats + sentSearch.gotResponse(); + /* + * check if we got enough search responses to cancel this search + * + * we will still use the data, even if the search is canceled. I + * mean, since it already made it here why not use it... + */ + if (sentSearch.getResponseNum() > mMaxSearchResponsesBeforeCancel) { + /* + * only send a cancel message once + */ + boolean sendCancel = false; + lock.lock(); + try { + if (!canceledSearches.containsKey(msg.getSearchID())) { + canceledSearches.put(msg.getSearchID(), System.currentTimeMillis()); + logger.finer(""canceling search "" + msg); + sendCancel = true; + } + } finally { + lock.unlock(); + } + if (sendCancel) { + overlayManager.sendSearchOrCancel(new OSF2FSearchCancel( + OSF2FMessage.CURRENT_VERSION, msg.getSearchID()), true, false); + } + } + if (search instanceof OSF2FHashSearch) { + // ok, it was a hash search that we sent + handleIncomingHashSearchResponse((OSF2FHashSearch) search, source, + (OSF2FHashSearchResp) msg); + } else if (search instanceof OSF2FTextSearch) { + // this was from a text search we sent + FileList fileList; + try { + OSF2FTextSearchResp textSearchResp = (OSF2FTextSearchResp) msg; + fileList = FileListManager.decode_basic(textSearchResp.getFileList()); + + textSearchManager.gotSearchResponse(search.getSearchID(), + source.getRemoteFriend(), fileList, textSearchResp.getChannelID(), + source.hashCode()); + + logger.fine(""results so far:""); + List res = getSearchResult(search.getSearchID()); + for (TextSearchResult textSearchResult : res) { + logger.fine(textSearchResult.toString()); + } + } catch (IOException e) { + logger.warning(""got malformed search response""); + } + } else { + logger.warning(""unknown search response type""); + } + } + // sentsearch == null + else { + // ok, this is for a search we forwarded + ForwardedSearch search; + lock.lock(); + try { + search = forwardedSearches.get(msg.getSearchID()); + if (search == null) { + logger.warning(""got response for unknown search:"" + source + "":"" + + msg.getDescription()); + return; + } + + logger.finest(""got response to forwarded search: "" + + search.getSearch().getDescription()); + + if (canceledSearches.containsKey(msg.getSearchID())) { + logger.finer(""not forwarding search, it is already canceled, "" + + msg.getSearchID()); + return; + } + } finally { + lock.unlock(); + } + + FriendConnection searcher = search.getSource(); + FriendConnection responder = source; + + if (search.getResponseNum() > mMaxSearchResponsesBeforeCancel) { + /* + * we really shouldn't cancel other peoples searches, but if + * they don't do it we have to + */ + lock.lock(); + try { + canceledSearches.put(msg.getSearchID(), System.currentTimeMillis()); + } finally { + lock.unlock(); + } + logger.finest(""Sending cancel for someone elses search!, searcher="" + + searcher.getRemoteFriend() + "" responder="" + responder.getRemoteFriend() + + "":\t"" + search); + overlayManager.forwardSearchOrCancel(source, new OSF2FSearchCancel( + OSF2FMessage.CURRENT_VERSION, msg.getSearchID())); + } else { + search.gotResponse(); + // register the forwarding + logger.finest(""registering overlay forward: "" + + searcher.getRemoteFriend().getNick() + ""<->"" + + responder.getRemoteFriend().getNick()); + try { + responder.registerOverlayForward(msg, searcher, search.getSearch(), false); + searcher.registerOverlayForward(msg, responder, search.getSearch(), true); + } catch (FriendConnection.OverlayRegistrationError e) { + String direction = ""'"" + responder.getRemoteFriend().getNick() + ""'->'"" + + searcher.getRemoteFriend().getNick() + ""'""; + e.direction = direction; + e.setupMessageSource = responder.getRemoteFriend().getNick(); + logger.warning(""not forwarding overlay setup request "" + direction + e.message); + debugChannelIdErrorSetupErrorStats.add(e); + return; + } + + // and send out the search + if (msg instanceof OSF2FHashSearchResp) { + searcher.sendChannelSetup((OSF2FHashSearchResp) msg.clone(), true); + } else if (msg instanceof OSF2FTextSearchResp) { + searcher.sendTextSearchResp((OSF2FTextSearchResp) msg.clone(), true); + } else { + Debug.out(""got unknown message: "" + msg.getDescription()); + } + } + } + + } + + /** + * + * @param source + * @param msg + * @return + */ + private boolean handleTextSearch(final FriendConnection source, final OSF2FTextSearch msg) { + + boolean shouldForward = true; + + if (logger.isLoggable(Level.FINER)) { + logger.finer(""handleTextSearch: "" + msg.getSearchString() + "" from "" + + source.getRemoteFriend().getNick()); + } + + String searchString = msg.getSearchString(); + + // common case is no filtering. + if (filteredKeywords.length > 0) { + StringTokenizer toks = new StringTokenizer(searchString); + + for (String filter : filteredKeywords) { + if (searchString.contains(filter)) { + logger.fine(""Blocking search due to filter: "" + searchString + "" matched by: "" + + filter); + return false; + } + } + } + + List results = filelistManager.handleSearch(source.getRemoteFriend(), + searchString); + + if (results.size() > 0) { + if (canRespondToSearch()) { + logger.finer(""found matches: "" + results.size()); + // long fileListSize = results.getFileNum(); + + List delayedExecutionTasks = new LinkedList(); + long time = System.currentTimeMillis(); + for (FileCollection c : results) { + // send back a response + int channelId = random.nextInt(); + LinkedList list = new LinkedList(); + list.add(c); + byte[] encoded = FileListManager.encode_basic(new FileList(list), false); + + final OSF2FTextSearchResp resp = new OSF2FTextSearchResp( + OSF2FMessage.CURRENT_VERSION, OSF2FMessage.FILE_LIST_TYPE_PARTIAL, + msg.getSearchID(), channelId, encoded); + int delay = overlayManager.getSearchDelayForInfohash(source.getRemoteFriend(), + c.getUniqueIdBytes()); + delayedExecutionTasks.add(new DelayedExecutionEntry(time + delay, 0, + new TimerTask() { + @Override + public void run() { + /* + * check if the search got canceled while we + * were sleeping + */ + if (!isSearchCanceled(msg.getSearchID())) { + source.sendTextSearchResp(resp, false); + } + } + })); + } + delayedExecutor.queue(delayedExecutionTasks); + + } else { + // not enough capacity :-( + shouldForward = false; + } + } + + return shouldForward; + } + + public void sendDirectedHashSearch(FriendConnection target, byte[] infoHash) { + + long metainfohashhash = filelistManager.getInfoHashhash(infoHash); + + int newSearchId = 0; + while (newSearchId == 0) { + newSearchId = random.nextInt(); + } + OSF2FHashSearch search = new OSF2FHashSearch(OSF2FMessage.CURRENT_VERSION, newSearchId, + metainfohashhash); + lock.lock(); + try { + sentSearches.put(newSearchId, new SentSearch(search)); + } finally { + lock.unlock(); + } + overlayManager.sendDirectedSearch(target, search); + + } + + public long getInfoHashHashFromSearchId(int searchId) { + lock.lock(); + try { + SentSearch sentSearch = sentSearches.get(searchId); + if (sentSearch != null && sentSearch.search instanceof OSF2FHashSearch) { + return ((OSF2FHashSearch) sentSearch.search).getInfohashhash(); + } + } finally { + lock.unlock(); + } + return -1; + } + + public void sendHashSearch(byte[] infoHash) { + long metainfohashhash = filelistManager.getInfoHashhash(infoHash); + + int newSearchId = 0; + while (newSearchId == 0) { + newSearchId = random.nextInt(); + } + OSF2FSearch search = new OSF2FHashSearch(OSF2FMessage.CURRENT_VERSION, newSearchId, + metainfohashhash); + + // these should go in the slow (forward) path so to route around slow + // nodes + sendSearch(newSearchId, search, false); + } + + private void sendSearch(int newSearchId, OSF2FSearch search, boolean skipQueue) { + lock.lock(); + try { + sentSearches.put(newSearchId, new SentSearch(search)); + } finally { + lock.unlock(); + } + overlayManager.sendSearchOrCancel(search, skipQueue, false); + } + + public int sendTextSearch(String searchString, TextSearchListener listener) { + int newSearchId = 0; + while (newSearchId == 0) { + newSearchId = random.nextInt(); + } + + if (FileCollection.containsKeyword(searchString)) { + searchString = searchString.replaceAll("":"", "";""); + searchString = handleKeyWords(searchString); + } + + OSF2FSearch search = new OSF2FTextSearch(OSF2FMessage.CURRENT_VERSION, + OSF2FMessage.FILE_LIST_TYPE_PARTIAL, newSearchId, searchString); + textSearchManager.sentSearch(newSearchId, searchString, listener); + sendSearch(newSearchId, search, false); + return newSearchId; + } + + private static String handleKeyWords(String searchString) { + searchString = FileCollection.removeWhiteSpaceAfteKeyChars(searchString); + String[] interestingKeyWords = new String[] { ""id"", ""sha1"", ""ed2k"" }; + int[] interestingKeyWordExectedKeyLen = { 20, 20, 16 }; + StringBuilder b = new StringBuilder(); + String[] split = searchString.split("" ""); + for (String s : split) { + // check for id + String toAdd = s; + for (int i = 0; i < interestingKeyWords.length; i++) { + String fromId = convertToBase64(s, interestingKeyWords[i], + interestingKeyWordExectedKeyLen[i]); + if (fromId != null) { + toAdd = fromId; + } + } + b.append(toAdd + "" ""); + if (!toAdd.equals(s)) { + logger.fine(""converted search: "" + s + ""->"" + toAdd); + } + } + return b.toString().trim(); + } + + private static String convertToBase64(String searchTerm, String _keyword, int expectedBytes) { + for (String sep : FileCollection.KEYWORDENDINGS) { + String keyword = _keyword + sep; + if (searchTerm.contains(keyword)) { + logger.finer(""converting base: "" + searchTerm); + try { + String baseXHash = searchTerm.substring(keyword.length()); + logger.finer(""basex hash: "" + baseXHash); + String hash = ShareManagerTools.baseXtoBase64(baseXHash, expectedBytes); + String toAdd = keyword + hash; + logger.finer(""new string: "" + toAdd); + return toAdd; + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + return null; + } + + static class DebugChannelIdEntry implements Comparable { + final int count; + final String name; + + public DebugChannelIdEntry(String name, int count) { + super(); + this.name = name; + this.count = count; + } + + public int compareTo(DebugChannelIdEntry o) { + if (o.count > count) { + return 1; + } else if (o.count == count) { + return 0; + } else { + return -1; + } + } + } + + private static class DebugChannelSetupErrorStats { + private final LinkedList errorList = new LinkedList(); + + int MAX_SIZE = 10000; + + public void add(FriendConnection.OverlayRegistrationError error) { + lock.lock(); + try { + if (errorList.size() > MAX_SIZE) { + errorList.removeLast(); + } + errorList.addFirst(error); + } finally { + lock.unlock(); + } + } + + public String getDebugStats() { + StringBuilder b = new StringBuilder(); + HashMap errorsPerFriend = new HashMap(); + HashMap errorsPerPair = new HashMap(); + lock.lock(); + try { + + for (FriendConnection.OverlayRegistrationError error : errorList) { + final String s = error.setupMessageSource; + if (!errorsPerFriend.containsKey(s)) { + errorsPerFriend.put(s, 0); + } + errorsPerFriend.put(s, errorsPerFriend.get(s) + 1); + + String d = error.direction; + if (!errorsPerPair.containsKey(d)) { + errorsPerPair.put(d, 0); + } + errorsPerPair.put(d, errorsPerPair.get(d) + 1); + } + + ArrayList friendTotalOrder = new ArrayList(); + for (String f : errorsPerFriend.keySet()) { + friendTotalOrder.add(new DebugChannelIdEntry(f, errorsPerFriend.get(f))); + } + Collections.sort(friendTotalOrder); + b.append(""by source:\n""); + for (DebugChannelIdEntry e : friendTotalOrder) { + b.append("" "" + e.name + "" "" + e.count + ""\n""); + } + + ArrayList byPairOrder = new ArrayList(); + for (String f : errorsPerPair.keySet()) { + byPairOrder.add(new DebugChannelIdEntry(f, errorsPerPair.get(f))); + } + Collections.sort(byPairOrder); + b.append(""by pair:\n""); + for (DebugChannelIdEntry e : byPairOrder) { + b.append("" "" + e.name + "" "" + e.count + ""\n""); + } + + } finally { + lock.unlock(); + } + return b.toString(); + } + } + + class DelayedSearchQueue { + + long lastSearchesPerSecondLogTime = 0; + long lastBytesPerSecondCount = 0; + int searchCount = 0; + + private long mDelay; + private final LinkedBlockingQueue queue = new LinkedBlockingQueue(); + private final HashMap queuedSearches = new HashMap(); + + public DelayedSearchQueue(long delay) { + this.mDelay = delay; + Thread t = new Thread(new DelayedSearchQueueThread()); + t.setDaemon(true); + t.setName(SEARCH_QUEUE_THREAD_NAME); + t.start(); + } + + /** + * Warning -- changing this won't re-order things already in the queue, + * so if you add something with a much smaller delay than the current + * head of the queue, it will wait until that's removed before sending + * the new message. + */ + public void setDelay(long inDelay) { + this.mDelay = inDelay; + } + + public void add(FriendConnection source, OSF2FSearch search) { + + if (lastSearchesPerSecondLogTime + 1000 < System.currentTimeMillis()) { + + lock.lock(); + try { + logger.fine(""Searches/sec: "" + searchCount + "" bytes: "" + + lastBytesPerSecondCount + "" searchQueueSize: "" + + queuedSearches.size()); + } finally { + lock.unlock(); + } + + lastSearchesPerSecondLogTime = System.currentTimeMillis(); + searchCount = 0; + lastBytesPerSecondCount = 0; + } + + searchCount++; + lastBytesPerSecondCount += FriendConnectionQueue.getMessageLen(search); + + lock.lock(); + try { + + // Flush the accounting info every 60 seconds + if (SearchManager.this.lastSearchAccountingFlush + 60 * 1000 < System + .currentTimeMillis()) { + lastSearchAccountingFlush = System.currentTimeMillis(); + searchesPerFriend.clear(); + } + + // If the search queue is more than half full, start dropping + // searches + // proportional to how much of the total queue each person is + // consuming + if (queuedSearches.size() > 0.25 * MAX_SEARCH_QUEUE_LENGTH) { + if (searchesPerFriend.containsKey(source.getRemoteFriend())) { + int outstanding = searchesPerFriend.get(source.getRemoteFriend()).v; + + // We add a hard limit on the number of searches from + // any one person. + if (outstanding > 0.15 * MAX_SEARCH_QUEUE_LENGTH) { + logger.fine(""Dropping due to 25% of total queue consumption "" + + source.getRemoteFriend().getNick() + "" "" + outstanding + + "" / "" + MAX_SEARCH_QUEUE_LENGTH); + return; + } + + // In other cases, we drop proportional to the + // consumption of the overall queue. + double acceptProb = (double) outstanding / (double) queuedSearches.size(); + if (random.nextDouble() < acceptProb) { + if (logger.isLoggable(Level.FINE)) { + logger.fine(""*** RED for search from "" + source + "" outstanding: "" + + outstanding + "" total: "" + queuedSearches.size()); + } + return; + } + } + } + + if (queuedSearches.size() > MAX_SEARCH_QUEUE_LENGTH) { + if (logger.isLoggable(Level.FINER)) { + logger.finer(""not forwarding search, queue length too large. id: "" + + search.getSearchID()); + } + return; + } + if (!queuedSearches.containsKey(search.getSearchID())) { + logger.finest(""adding search to forward queue, will forward in "" + mDelay + + "" ms""); + DelayedSearchQueueEntry entry = new DelayedSearchQueueEntry(search, source, + System.currentTimeMillis() + mDelay); + + if (searchesPerFriend.containsKey(source.getRemoteFriend()) == false) { + searchesPerFriend.put(source.getRemoteFriend(), + new SearchManager.MutableInteger()); + } + searchesPerFriend.get(source.getRemoteFriend()).v++; + logger.finest(""Search for friend: "" + source.getRemoteFriend().getNick() + "" "" + + searchesPerFriend.get(source.getRemoteFriend()).v); + + queuedSearches.put(search.getSearchID(), entry); + queue.add(entry); + + } else { + logger.finer(""search already in queue, not adding""); + } + } finally { + lock.unlock(); + } + } + + /* + * make sure to already have the lock when calling this + */ + public boolean isQueued(OSF2FSearch search) { + return queuedSearches.containsKey(search.getSearchID()); + } + + class DelayedSearchQueueThread implements Runnable { + + public void run() { + while (true) { + try { + DelayedSearchQueueEntry e = queue.take(); + long timeUntilSend = e.dontSendBefore - System.currentTimeMillis(); + if (timeUntilSend > 0) { + logger.finer(""got search ("" + e.search.getDescription() + + "") to forward, waiting "" + timeUntilSend + + "" ms until sending""); + Thread.sleep(timeUntilSend); + } + forwardSearch(e.source, e.search); + /* + * remove the search from the queuedSearchesMap + */ + lock.lock(); + try { + queuedSearches.remove(e.search.getSearchID()); + // If searchesPerFriend was flushed while this + // search was in the + // queue, the get() call will return null. + if (searchesPerFriend.containsKey(e.source.getRemoteFriend())) { + searchesPerFriend.get(e.source.getRemoteFriend()).v--; + } + } finally { + lock.unlock(); + } + /* + * if we didn't sleep at all, sleep the min time between + * searches + */ + if (timeUntilSend < 1) { + double ms = 1000.0 / FriendConnection.MAX_OUTGOING_SEARCH_RATE; + int msFloor = (int) Math.floor(ms); + int nanosLeft = (int) Math.round((ms - msFloor) * 1000000.0); + logger.finest(""sleeping "" + msFloor + ""ms + "" + nanosLeft + "" ns""); + Thread.sleep(msFloor, Math.min(999999, nanosLeft)); + } + + } catch (Exception e1) { + logger.warning(""*** Delayed search queue thread error: "" + e1.toString()); + e1.printStackTrace(); + BackendErrorLog.get().logException(e1); + } + } + } + } + } + + static class DelayedSearchQueueEntry { + final long dontSendBefore; + final OSF2FSearch search; + final FriendConnection source; + final long insertionTime; + + public DelayedSearchQueueEntry(OSF2FSearch search, FriendConnection source, + long dontSendBefore) { + this.insertionTime = System.currentTimeMillis(); + this.search = search; + this.source = source; + this.dontSendBefore = dontSendBefore; + } + } + + class ForwardedSearch { + private int responsesForwarded = 0; + private final OSF2FSearch search; + private final FriendConnection source; + private final long time; + + public ForwardedSearch(FriendConnection source, OSF2FSearch search) { + this.time = System.currentTimeMillis(); + this.source = source; + this.search = search; + + } + + public long getAge() { + return System.currentTimeMillis() - this.time; + } + + public int getResponseNum() { + return responsesForwarded; + } + + public OSF2FSearch getSearch() { + return search; + } + + public int getSearchId() { + return search.getSearchID(); + } + + public FriendConnection getSource() { + return source; + } + + public void gotResponse() { + responsesForwarded++; + } + + public boolean isTimedOut() { + return getAge() > MAX_SEARCH_AGE; + } + } + + static class RotatingBloomFilter { + private static final int OBJECTS_TO_STORE = 1000000; + + private static final int SIZE_IN_BITS = 10240 * 1024; + + private long currentFilterCreated; + private final LinkedList filters = new LinkedList(); + private final int maxBuckets; + private final long maxFilterAge; + + public RotatingBloomFilter(long totalAge, int buckets) { + this.maxBuckets = buckets; + this.maxFilterAge = (totalAge / buckets) + 1; + rotate(); + } + + public boolean contains(int searchId, int searchValue) { + byte[] bytes = bytesFromInts(searchId, searchValue); + for (BloomFilter f : filters) { + if (f.test(bytes)) { + return true; + } + } + + return false; + } + + public double getPrevFilterFalsePositiveEst() { + if (filters.size() > 1) { + return filters.get(1).getPredictedFalsePositiveRate(); + } else { + return filters.getFirst().getPredictedFalsePositiveRate(); + } + } + + public int getPrevFilterNumElements() { + if (filters.size() > 1) { + return filters.get(1).getUniqueObjectsStored(); + } else { + return filters.getFirst().getUniqueObjectsStored(); + } + } + + public void insert(int searchId, int searchValue) { + byte[] bytes = bytesFromInts(searchId, searchValue); + filters.getFirst().insert(bytes); + } + + private void rotate() { + + if (filters.size() > 0) { + BloomFilter prevFilter = filters.getFirst(); + String str = ""Rotating bloom filter: objects="" + + prevFilter.getUniqueObjectsStored() + "" predicted false positive rate="" + + (100 * prevFilter.getPredictedFalsePositiveRate() + ""%""); + logger.info(str); + } + currentFilterCreated = System.currentTimeMillis(); + try { + filters.addFirst(new BloomFilter(SIZE_IN_BITS, OBJECTS_TO_STORE)); + } catch (NoSuchAlgorithmException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + if (filters.size() > maxBuckets) { + filters.removeLast(); + } + } + + public boolean rotateIfNeeded() { + long currentFilterAge = System.currentTimeMillis() - currentFilterCreated; + if (currentFilterAge > maxFilterAge) { + rotate(); + return true; + } + return false; + } + + private static byte[] bytesFromInts(int int1, int int2) { + byte[] bytes = new byte[8]; + + bytes[0] = (byte) (int1 >>> 24); + bytes[1] = (byte) (int1 >>> 16); + bytes[2] = (byte) (int1 >>> 8); + bytes[3] = (byte) int1; + + bytes[4] = (byte) (int2 >>> 24); + bytes[5] = (byte) (int2 >>> 16); + bytes[6] = (byte) (int2 >>> 8); + bytes[7] = (byte) int2; + return bytes; + } + + public static void main(String[] args) { + OSF2FMain.getSingelton(); + logger.setLevel(Level.FINE); + Random rand = new Random(); + + RotatingBloomFilter bf = new RotatingBloomFilter(60 * 1000, 4); + + Set inserts = new HashSet(); + for (int j = 0; j < 8; j++) { + for (int i = 0; i < 20000; i++) { + int r1 = rand.nextInt(); + int r2 = rand.nextInt(); + byte[] bytes = bytesFromInts(r1, r2); + inserts.add(new String(Base64.encode(bytes))); + bf.insert(r1, r2); + if (!bf.contains(r1, r2)) { + System.err.println(""insert failes (does not contain it anymore)""); + } + } + bf.rotate(); + } + + int fps = 0, to_check = 200000; + for (int i = 0; i < to_check; i++) { + int int1; + int int2; + byte[] bytes; + do { + int1 = rand.nextInt(); + int2 = rand.nextInt(); + bytes = bytesFromInts(int1, int2); + } while (inserts.contains(new String(Base64.encode(bytes))) == true); + if (bf.contains(int1, int2) == true) + fps++; + } + + System.out.println(""false positive check, "" + fps + ""/"" + to_check); + + System.out.println(""mem: "" + + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); + + } + + } + + class SentSearch { + private int responses = 0; + private final OSF2FSearch search; + + private final long time; + + public SentSearch(OSF2FSearch search) { + this.search = search; + this.time = System.currentTimeMillis(); + } + + public long getAge() { + return System.currentTimeMillis() - this.time; + } + + public int getResponseNum() { + return responses; + } + + public OSF2FSearch getSearch() { + return search; + } + + public void gotResponse() { + responses++; + } + + public boolean isTimedOut() { + return getAge() > MAX_SEARCH_AGE; + } + + } + + public interface TextSearchListener { + public void searchResponseReceived(TextSearchResponseItem r); + } + + class TextSearchManager { + private final ConcurrentHashMap responses; + private final ConcurrentHashMap listeners; + + public TextSearchManager() { + responses = new ConcurrentHashMap(); + listeners = new ConcurrentHashMap(); + } + + public List getResults(int searchId) { + TextSearchResponse resps = responses.get(searchId); + + HashMap result = new HashMap(); + + if (resps != null) { + /* + * group into file collections + */ + for (TextSearchResponseItem item : resps.getItems()) { + for (FileCollection collection : item.getFileList().getElements()) { + if (result.containsKey(collection.getUniqueID())) { + TextSearchResult existing = result.get(collection.getUniqueID()); + existing.merge(item, collection); + } else { + // mark stuff that we already have + boolean alreadyInLibrary = true; + GlobalManager globalManager = AzureusCoreImpl.getSingleton() + .getGlobalManager(); + DownloadManager dm = globalManager.getDownloadManager(new HashWrapper( + collection.getUniqueIdBytes())); + if (dm == null) { + alreadyInLibrary = false; + } + result.put(collection.getUniqueID(), new TextSearchResult(item, + collection, alreadyInLibrary)); + } + } + } + + // /* + // * verify that we didn't get any bad data + // */ + // for (TextSearchResult item : result.values()) { + // FileCollection collection = item.getCollection(); + // String searchString = resps.getSearchString(); + // boolean collectionMatch = collection.nameMatch(searchString); + // + // Set filteredFiles = new + // HashSet(); + // List allChildren = collection.getChildren(); + // for (int i = 0; i < allChildren.size(); i++) { + // FileListFile f = allChildren.get(i); + // if (filteredFiles.contains(f)) { + // continue; + // } + // if (collectionMatch) { + // filteredFiles.add(f); + // } else if (f.searchMatch(searchString)) { + // filteredFiles.add(f); + // } else { + // logger.fine(""got search result that doesn't match search: "" + + // f.getFileName() + "" ! "" + searchString); + // } + // } + // logger.fine(collection.getName() + "" totalResp: "" + + // allChildren.size() + "" afterFiler="" + filteredFiles.size()); + // collection.setChildren(new + // ArrayList(filteredFiles)); + // } + + return new ArrayList(result.values()); + } + logger.fine(""no responses for searchId="" + searchId); + return new ArrayList(); + } + + public void gotSearchResponse(int searchId, Friend throughFriend, FileList fileList, + int channelId, int connectionId) { + TextSearchResponse r = responses.get(searchId); + if (r != null) { + long age = System.currentTimeMillis() - r.getTime(); + TextSearchResponseItem item = new TextSearchResponseItem(throughFriend, fileList, + age, channelId, connectionId); + r.add(item); + TextSearchListener listener = listeners.get(searchId); + if (listener != null) { + listener.searchResponseReceived(item); + } + } else { + logger.warning(""got response for unknown search""); + } + } + + public void sentSearch(int searchId, String searchString, TextSearchListener listener) { + responses.put(searchId, new TextSearchResponse(searchString)); + if (listener != null) { + listeners.put(searchId, listener); + } + } + + public void clearOldResponses() { + for (Iterator iterator = responses.keySet().iterator(); iterator.hasNext();) { + Integer key = iterator.next(); + TextSearchResponse response = responses.get(key); + if (System.currentTimeMillis() - response.getTime() > 10 * 60 * 1000) { + iterator.remove(); + listeners.remove(key); + } + + } + } + } + + public boolean isSearchInBloomFilter(OSF2FSearch search) { + lock.lock(); + try { + int searchID = search.getSearchID(); + int valueID = search.getValueID(); + if (recentSearches.contains(searchID, valueID)) { + bloomSearchesBlockedCurr++; + } + } finally { + lock.unlock(); + } + return false; + } } diff --git a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/ServiceConnection.java b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/ServiceConnection.java index e1112dfd..b410524f 100644 --- a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/ServiceConnection.java +++ b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/network/ServiceConnection.java @@ -1,10 +1,188 @@ package edu.washington.cs.oneswarm.f2f.network; -public class ServiceConnection extends OverlayTransport { +import java.nio.ByteBuffer; +import java.util.LinkedList; +import java.util.logging.Logger; - public ServiceConnection(FriendConnection connection, int channelId, byte[] infohash, - int pathID, boolean outgoing, long overlayDelayMs) { - super(connection, channelId, infohash, pathID, outgoing, overlayDelayMs); +import org.gudy.azureus2.core3.util.DirectByteBuffer; + +import com.aelitis.azureus.core.networkmanager.IncomingMessageQueue.MessageQueueListener; +import com.aelitis.azureus.core.networkmanager.NetworkConnection; +import com.aelitis.azureus.core.networkmanager.NetworkConnection.ConnectionListener; +import com.aelitis.azureus.core.peermanager.messaging.Message; + +import edu.washington.cs.oneswarm.f2f.messaging.OSF2FChannelDataMsg; +import edu.washington.cs.oneswarm.f2f.servicesharing.DataMessage; +import edu.washington.cs.oneswarm.f2f.servicesharing.ServiceSharingManager.SharedService; + +public class ServiceConnection extends OverlayEndpoint { + /** + ** High level ** + * + * Searcher: Register service, enter local port and searchkey, Open local + * port, On incoming connection: Search + * + * + * Service host: Search hit->Search reply->contact server On server timeout + * or any other error: send channel reset + * + * Searcher: On search reply: send any incoming data to the channel + * + */ + + /** + ** Details ** + * + * For service host: + * + * Create: Create new network connection, register the network connection to + * handle rate limited reads/writes. + * + * Server->Overlay: On incoming message: move the payload into a new overlay + * message with the proper channel id and queue on the friend connection. + * The new message now owns the payload and is responsible for destroying + * it. + * + * Overlay->Server: put the message in the outgoing queue on the server + * connection. + */ + + private final static Logger logger = Logger.getLogger(ServiceConnection.class.getName()); + // all operations on this object must be in a synchronized block + private final LinkedList bufferedMessages; + private NetworkConnection serverConnection; + + private final SharedService service; + private final boolean serverSide; + + public ServiceConnection(SharedService service, FriendConnection connection, int channelId, + int pathID, boolean serverSide) { + super(connection, channelId, pathID, 0); + this.service = service; + this.bufferedMessages = new LinkedList(); + this.serverSide = true; + } + + @Override + public void cleanup() { + serverConnection.close(); + } + + @Override + protected void destroyBufferedMessages() { + synchronized (bufferedMessages) { + while (bufferedMessages.size() > 0) { + bufferedMessages.removeFirst().destroy(); + } + } + }; + + @Override + public String getDescription() { + return super.getDescription() + "" "" + service.toString() + "" serverside="" + serverSide; + } + + @Override + protected void handleDelayedOverlayMessage(OSF2FChannelDataMsg msg) { + if (closed) { + return; + } + if (!started) { + start(); + } + if (!serverConnection.isConnected()) { + synchronized (bufferedMessages) { + bufferedMessages.add(msg); + } + return; + } + writeMessageToServerConnection(msg.getData()); + } + + /** + * Currently we connect to the server when we get the first message data. + */ + // TODO (isdal): connect to the server on incoming search message and send + // reply on successful connect? + @Override + public void start() { + logger.fine(getDescription() + "" starting""); + if (isStarted()) { + logger.warning(""Tried to start already started service""); + return; + } + if (!service.isEnabled()) { + logger.fine(""Tried to start disabled connection""); + return; + } + serverConnection = service.createConnection(new ConnectionListener() { + @Override + public void connectFailure(Throwable failure_msg) { + logger.fine(ServiceConnection.this.getDescription() + "" connection failure""); + ServiceConnection.this.close(""Exception during connect""); + } + + @Override + public void connectStarted() { + logger.fine(ServiceConnection.this.getDescription() + "" connect started""); + } + + @Override + public void connectSuccess(ByteBuffer remaining_initial_data) { + logger.fine(ServiceConnection.this.getDescription() + "" connected""); + serverConnection.getIncomingMessageQueue().registerQueueListener( + new ServerIncomingMessageListener()); + synchronized (bufferedMessages) { + for (OSF2FChannelDataMsg msg : bufferedMessages) { + logger.finest(""sending queued message: "" + msg.getDescription()); + writeMessageToServerConnection(msg.getData()); + } + } + } + + @Override + public void exceptionThrown(Throwable error) { + ServiceConnection.this.close(""Exception during connect""); + } + + @Override + public String getDescription() { + return ServiceConnection.this.getDescription() + "" connect listener""; + } + }); + started = true; } + private void writeMessageToServerConnection(DirectByteBuffer[] data) { + for (DirectByteBuffer directByteBuffer : data) { + DataMessage msg = new DataMessage(directByteBuffer); + logger.finest(""writing message to server queue: "" + msg.getDescription()); + serverConnection.getOutgoingMessageQueue().addMessage(msg, false); + } + } + + private class ServerIncomingMessageListener implements MessageQueueListener { + + @Override + public void dataBytesReceived(int byte_count) { + } + + @Override + public boolean messageReceived(Message message) { + logger.finest(""Message from server: "" + message.getDescription()); + if (!(message instanceof DataMessage)) { + String msg = ""got wrong message type from server: ""; + logger.warning(msg + message.getDescription()); + ServiceConnection.this.close(msg); + return false; + } + DataMessage dataMessage = (DataMessage) message; + ServiceConnection.this.writeMessageToFriendConnection(dataMessage.transferPayload()); + return true; + } + + @Override + public void protocolBytesReceived(int byte_count) { + } + } } diff --git a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/servicesharing/DataMessage.java b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/servicesharing/DataMessage.java index 11fc62b7..2070626c 100644 --- a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/servicesharing/DataMessage.java +++ b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/servicesharing/DataMessage.java @@ -15,16 +15,26 @@ import com.aelitis.azureus.core.peermanager.messaging.MessageStreamDecoder; import com.aelitis.azureus.core.peermanager.messaging.MessageStreamEncoder; +import edu.washington.cs.oneswarm.f2f.messaging.OSF2FChannelDataMsg; import edu.washington.cs.oneswarm.f2f.messaging.OSF2FMessage; -class DataMessage implements Message { +public class DataMessage extends OSF2FChannelDataMsg { + private static final byte SS = DirectByteBuffer.SS_MSG; private DirectByteBuffer buffer = null; private static String ID = ""RAW_MESSAGE""; - private final String DESC = ""Raw message""; + private final String desc; + private final int size; public DataMessage(DirectByteBuffer _buffer) { - buffer = _buffer; + super(OSF2FMessage.CURRENT_VERSION, 1, _buffer); + size = _buffer.remaining(SS); + desc = ""Raw message: "" + size + "" bytes""; + } + + @Override + public int getMessageSize() { + return size; } public String getID() { @@ -48,7 +58,7 @@ public int getType() { } public String getDescription() { - return DESC; + return desc; } public byte getVersion() { @@ -64,11 +74,26 @@ public DirectByteBuffer[] getData() { } public Message deserialize(DirectByteBuffer data, byte version) throws MessageException { - throw (new MessageException(""not imp"")); + throw (new MessageException(""not implemented"")); } public void destroy() { - buffer.returnToPool(); + if (buffer != null) { + buffer.returnToPool(); + } + } + + /** + * Retrieve the payload from this message for transfer into a new message. + * + * The new message is responsible for returning the buffer on destroy. + * + * @return + */ + public DirectByteBuffer transferPayload() { + DirectByteBuffer data = buffer; + buffer = null; + return data; } static class RawMessageEncoder implements MessageStreamEncoder { @@ -81,7 +106,6 @@ public RawMessage[] encodeMessage(Message base_message) { } static class RawMessageDecoder implements MessageStreamDecoder { - private static final byte SS = DirectByteBuffer.SS_MSG; private static int MAX_PAYLOAD = OSF2FMessage.MAX_PAYLOAD_SIZE; DirectByteBuffer payload_buffer; @@ -111,6 +135,9 @@ public int performStreamDecode(Transport transport, int max_bytes) throws IOExce if (payload_buffer == null) { payload_buffer = DirectByteBufferPool.getBuffer(SS, MAX_PAYLOAD); } + if (paused) { + break; + } long read = transport.read(new ByteBuffer[] { payload_buffer.getBuffer(SS) }, 0, bytes_left); bytes_left -= read; @@ -119,11 +146,12 @@ public int performStreamDecode(Transport transport, int max_bytes) throws IOExce // * transport has no more data if (payload_buffer.remaining(SS) == 0 || read == 0) { if (payload_buffer.position(SS) > 0) { + payload_buffer.position(SS, 0); Message msg = new DataMessage(payload_buffer); messages_last_read.add(msg); payload_buffer = null; } - // If transport has no more data, break + // If we read all from transport, break if (read == 0) { break; } @@ -169,5 +197,4 @@ public ByteBuffer destroy() { return ByteBuffer.allocate(0); } } - } \ No newline at end of file diff --git a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/servicesharing/ServiceSharingManager.java b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/servicesharing/ServiceSharingManager.java index 4a920db9..1d3d544e 100644 --- a/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/servicesharing/ServiceSharingManager.java +++ b/oneswarm_f2f/src/edu/washington/cs/oneswarm/f2f/servicesharing/ServiceSharingManager.java @@ -1,40 +1,78 @@ package edu.washington.cs.oneswarm.f2f.servicesharing; import java.net.InetSocketAddress; -import java.util.concurrent.ConcurrentHashMap; +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.logging.Logger; import com.aelitis.azureus.core.networkmanager.ConnectionEndpoint; import com.aelitis.azureus.core.networkmanager.NetworkConnection; +import com.aelitis.azureus.core.networkmanager.NetworkConnection.ConnectionListener; import com.aelitis.azureus.core.networkmanager.NetworkManager; +import edu.washington.cs.oneswarm.f2f.BigFatLock; import edu.washington.cs.oneswarm.f2f.messaging.OSF2FHashSearch; +import edu.washington.cs.oneswarm.f2f.network.OverlayManager; import edu.washington.cs.oneswarm.f2f.servicesharing.DataMessage.RawMessageDecoder; import edu.washington.cs.oneswarm.f2f.servicesharing.DataMessage.RawMessageEncoder; public class ServiceSharingManager { - private final static ServiceSharingManager instace = new ServiceSharingManager(); + private final static ServiceSharingManager instance = new ServiceSharingManager(); + + private static BigFatLock lock = OverlayManager.lock; + + private final static Logger logger = Logger.getLogger(ServiceSharingManager.class.getName()); public static ServiceSharingManager getInstance() { - return instace; + return instance; } private ServiceSharingManager() { } - public ConcurrentHashMap services = new ConcurrentHashMap(); + public HashMap serverServices = new HashMap(); + + public void registerServerService(long searchkey, SharedService service) { + try { + lock.lock(); + serverServices.put(searchkey, service); + } finally { + lock.unlock(); + } + + } + + public void deregisterServerService(long searchKey) { + try { + lock.lock(); + serverServices.remove(searchKey); + } finally { + lock.unlock(); + } - public void registerService(long searchkey, Service service) { - services.put(searchkey, service); } - public Service handleSearch(OSF2FHashSearch search) { - Service service = services.get(search.getInfohashhash()); + public SharedService handleSearch(OSF2FHashSearch search) { + SharedService service = null; + try { + lock.lock(); + service = serverServices.get(search.getInfohashhash()); + } finally { + lock.unlock(); + } + + if (service == null || !service.isEnabled()) { + return null; + } return service; } - static class Service { - public Service(InetSocketAddress address, String name) { + public static class SharedService { + // Time the service is disabled after a failed connect attempt; + public static final long FAILURE_BACKOFF = 60 * 1000; + + public SharedService(InetSocketAddress address, String name) { super(); this.address = address; this.name = name; @@ -42,13 +80,53 @@ public Service(InetSocketAddress address, String name) { private final InetSocketAddress address; private final String name; + private long lastFailedConnect; - public NetworkConnection createConnection() { + public boolean isEnabled() { + long lastFailedAge = System.currentTimeMillis() - lastFailedConnect; + boolean enabled = lastFailedAge > FAILURE_BACKOFF; + logger.finer(String.format(""Service %s is disabled, last failure: %d seconds ago"", + name, lastFailedAge)); + return enabled; + } + + public NetworkConnection createConnection(final ConnectionListener listener) { ConnectionEndpoint target = new ConnectionEndpoint(address); NetworkConnection conn = NetworkManager.getSingleton().createConnection(target, new RawMessageEncoder(), new RawMessageDecoder(), false, false, new byte[0][0]); + conn.connect(false, new ConnectionListener() { + + @Override + public String getDescription() { + return name + ""Listener""; + } + + @Override + public void exceptionThrown(Throwable error) { + listener.exceptionThrown(error); + } + + @Override + public void connectSuccess(ByteBuffer remaining_initial_data) { + listener.connectSuccess(remaining_initial_data); + } + + @Override + public void connectStarted() { + listener.connectStarted(); + } + + @Override + public void connectFailure(Throwable failure_msg) { + lastFailedConnect = System.currentTimeMillis(); + listener.connectFailure(failure_msg); + } + }); return conn; + } + public String toString() { + return name + "" "" + address; } } }" f64233fb2d9bcb77e9249d3bc497fd9d110e6a9f,ReactiveX-RxJava,Add Single.fromCallable()--,a,https://github.com/ReactiveX/RxJava,"diff --git a/src/main/java/rx/Single.java b/src/main/java/rx/Single.java index 4324d32acf..3701d93189 100644 --- a/src/main/java/rx/Single.java +++ b/src/main/java/rx/Single.java @@ -12,6 +12,7 @@ */ package rx; +import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @@ -605,6 +606,43 @@ public final static Single from(Future future, Scheduler sch return new Single(OnSubscribeToObservableFuture.toObservableFuture(future)).subscribeOn(scheduler); } + /** + * Returns a {@link Single} that invokes passed function and emits its result for each new Observer that subscribes. + *

+ * Allows you to defer execution of passed function until Observer subscribes to the {@link Single}. + * It makes passed function ""lazy"". + * Result of the function invocation will be emitted by the {@link Single}. + *

+ *
Scheduler:
+ *
{@code fromCallable} does not operate by default on a particular {@link Scheduler}.
+ *
+ * + * @param func + * function which execution should be deferred, it will be invoked when Observer will subscribe to the {@link Single}. + * @param + * the type of the item emitted by the {@link Single}. + * @return a {@link Single} whose {@link Observer}s' subscriptions trigger an invocation of the given function. + */ + @Experimental + public static Single fromCallable(final Callable func) { + return create(new OnSubscribe() { + @Override + public void call(SingleSubscriber singleSubscriber) { + final T value; + + try { + value = func.call(); + } catch (Throwable t) { + Exceptions.throwIfFatal(t); + singleSubscriber.onError(t); + return; + } + + singleSubscriber.onSuccess(value); + } + }); + } + /** * Returns a {@code Single} that emits a specified item. *

diff --git a/src/test/java/rx/SingleTest.java b/src/test/java/rx/SingleTest.java index 7d8fe2dc22..f78151b094 100644 --- a/src/test/java/rx/SingleTest.java +++ b/src/test/java/rx/SingleTest.java @@ -20,8 +20,10 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; import java.util.Arrays; +import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @@ -530,4 +532,42 @@ public void doOnErrorShouldThrowCompositeExceptionIfOnErrorActionThrows() { verify(action).call(error); } + + @Test + public void shouldEmitValueFromCallable() throws Exception { + Callable callable = mock(Callable.class); + + when(callable.call()).thenReturn(""value""); + + TestSubscriber testSubscriber = new TestSubscriber(); + + Single + .fromCallable(callable) + .subscribe(testSubscriber); + + testSubscriber.assertValue(""value""); + testSubscriber.assertNoErrors(); + + verify(callable).call(); + } + + @Test + public void shouldPassErrorFromCallable() throws Exception { + Callable callable = mock(Callable.class); + + Throwable error = new IllegalStateException(); + + when(callable.call()).thenThrow(error); + + TestSubscriber testSubscriber = new TestSubscriber(); + + Single + .fromCallable(callable) + .subscribe(testSubscriber); + + testSubscriber.assertNoValues(); + testSubscriber.assertError(error); + + verify(callable).call(); + } }" e2ffe19d36e25a9d208e53a534f878e8605ed5ab,intellij-community,cleanup--,p,https://github.com/JetBrains/intellij-community,"diff --git a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java index a34084fa28eaf..6fb2c80e3d801 100644 --- a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java +++ b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java @@ -137,7 +137,7 @@ public Boolean fun(String s) { private final CompileServerClasspathManager myClasspathManager = new CompileServerClasspathManager(); private final Executor myPooledThreadExecutor = new Executor() { @Override - public void execute(Runnable command) { + public void execute(@NotNull Runnable command) { ApplicationManager.getApplication().executeOnPooledThread(command); } }; @@ -478,7 +478,7 @@ public void run() { globals = buildGlobalSettings(); myGlobals = globals; } - CmdlineRemoteProto.Message.ControllerMessage.FSEvent currentFSChanges = null; + CmdlineRemoteProto.Message.ControllerMessage.FSEvent currentFSChanges; final SequentialTaskExecutor projectTaskQueue; synchronized (myProjectDataMap) { ProjectData data = myProjectDataMap.get(projectPath); @@ -761,21 +761,12 @@ private Process launchBuildProcess(Project project, final int port, final UUID s cmdLine.addParameter(""-D""+ GlobalOptions.HOSTNAME_OPTION + ""="" + host); // javac's VM should use the same default locale that IDEA uses in order for javac to print messages in 'correct' language - final String lang = System.getProperty(""user.language""); - if (lang != null) { - //noinspection HardCodedStringLiteral - cmdLine.addParameter(""-Duser.language="" + lang); - } - final String country = System.getProperty(""user.country""); - if (country != null) { - //noinspection HardCodedStringLiteral - cmdLine.addParameter(""-Duser.country="" + country); - } - //noinspection HardCodedStringLiteral - final String region = System.getProperty(""user.region""); - if (region != null) { - //noinspection HardCodedStringLiteral - cmdLine.addParameter(""-Duser.region="" + region); + String[] propertyNames = {""user.language"", ""user.country"", ""user.region""}; + for (String name : propertyNames) { + final String value = System.getProperty(name); + if (value != null) { + cmdLine.addParameter(""-D"" + name + ""="" + value); + } } cmdLine.addParameter(""-classpath""); diff --git a/jps/jps-builders/src/org/jetbrains/jps/api/CmdlineProtoUtil.java b/jps/jps-builders/src/org/jetbrains/jps/api/CmdlineProtoUtil.java index 38d0aa113a458..ac843603c68b7 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/api/CmdlineProtoUtil.java +++ b/jps/jps-builders/src/org/jetbrains/jps/api/CmdlineProtoUtil.java @@ -22,7 +22,7 @@ public static CmdlineRemoteProto.Message.ControllerMessage createMakeRequest(Str List scopes, final Map userData, final CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings globals, - final CmdlineRemoteProto.Message.ControllerMessage.FSEvent event) { + final @Nullable CmdlineRemoteProto.Message.ControllerMessage.FSEvent event) { return createBuildParametersMessage(CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.Type.MAKE, project, scopes, userData, Collections.emptyList(), globals, event); @@ -33,7 +33,7 @@ public static CmdlineRemoteProto.Message.ControllerMessage createForceCompileReq Collection paths, final Map userData, final CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings globals, - final CmdlineRemoteProto.Message.ControllerMessage.FSEvent event) { + final @Nullable CmdlineRemoteProto.Message.ControllerMessage.FSEvent event) { return createBuildParametersMessage(CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.Type.FORCED_COMPILATION, project, scopes, userData, paths, globals, event); } @@ -63,7 +63,7 @@ public static TargetTypeBuildScope createAllTargetsScope(BuildTargetType type private static CmdlineRemoteProto.Message.ControllerMessage createBuildParametersMessage(CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.Type buildType, String project, - List scopes, + List scopes, Map userData, Collection paths, final CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings globals, @@ -99,7 +99,7 @@ public static CmdlineRemoteProto.Message.KeyValuePair createPair(String key, Str } - public static CmdlineRemoteProto.Message.Failure createFailure(String description, Throwable cause) { + public static CmdlineRemoteProto.Message.Failure createFailure(String description, @Nullable Throwable cause) { final CmdlineRemoteProto.Message.Failure.Builder builder = CmdlineRemoteProto.Message.Failure.newBuilder(); builder.setDescription(description); if (cause != null) {" 6236c422615cfe33795267214077551f3d9ffa6f,camel,CAMEL-1977: Http based components should filter- out camel internal headers.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@814567 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/camel,"diff --git a/components/camel-http/src/main/java/org/apache/camel/component/http/HttpHeaderFilterStrategy.java b/components/camel-http/src/main/java/org/apache/camel/component/http/HttpHeaderFilterStrategy.java index a32be75c50c52..37e81e5c902f3 100644 --- a/components/camel-http/src/main/java/org/apache/camel/component/http/HttpHeaderFilterStrategy.java +++ b/components/camel-http/src/main/java/org/apache/camel/component/http/HttpHeaderFilterStrategy.java @@ -45,6 +45,7 @@ protected void initialize() { setLowerCase(true); // filter headers begin with ""Camel"" or ""org.apache.camel"" - setOutFilterPattern(""(Camel|org\\.apache\\.camel)[\\.|a-z|A-z|0-9]*""); + // must ignore case for Http based transports + setOutFilterPattern(""(?i)(Camel|org\\.apache\\.camel)[\\.|a-z|A-z|0-9]*""); } } diff --git a/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpFilterCamelHeadersTest.java b/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpFilterCamelHeadersTest.java new file mode 100644 index 0000000000000..40861c7fcc891 --- /dev/null +++ b/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpFilterCamelHeadersTest.java @@ -0,0 +1,80 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the ""License""); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.jetty; + +import java.util.Map; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.impl.JndiRegistry; +import org.apache.camel.test.junit4.CamelTestSupport; +import org.junit.Test; + +/** + * @version $Revision$ + */ +public class HttpFilterCamelHeadersTest extends CamelTestSupport { + + @Test + public void testFilterCamelHeaders() throws Exception { + Exchange out = template.send(""http://localhost:9090/test/filter"", new Processor() { + public void process(Exchange exchange) throws Exception { + exchange.getIn().setBody(""Claus""); + exchange.getIn().setHeader(""bar"", 123); + } + }); + + assertNotNull(out); + assertEquals(""Hi Claus"", out.getOut().getBody(String.class)); + + // there should be no internal Camel headers + // except for the response code + Map headers = out.getOut().getHeaders(); + for (String key : headers.keySet()) { + if (!key.equalsIgnoreCase(Exchange.HTTP_RESPONSE_CODE)) { + assertTrue(""Should not contain any Camel internal headers"", !key.toLowerCase().startsWith(""camel"")); + } else { + assertEquals(200, headers.get(Exchange.HTTP_RESPONSE_CODE)); + } + } + } + + @Override + protected JndiRegistry createRegistry() throws Exception { + JndiRegistry jndi = super.createRegistry(); + jndi.bind(""foo"", new MyFooBean()); + return jndi; + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + from(""jetty:http://localhost:9090/test/filter"").beanRef(""foo""); + } + }; + } + + public static class MyFooBean { + + public String hello(String name) { + return ""Hi "" + name; + } + } +}" e931ef7e6e360b1a89e3f0d97fbc8332852b8dcd,intellij-community,move suppress/settings intention down- (IDEA-72320 )--,c,https://github.com/JetBrains/intellij-community,"diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/emptyIntention/LowPriority.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/emptyIntention/LowPriority.java new file mode 100644 index 0000000000000..51882b4824e92 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/emptyIntention/LowPriority.java @@ -0,0 +1,6 @@ +class Test { + void method() { + final String i = """"; + i = """"; + } +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/EmptyIntentionInspectionQuickFixTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/EmptyIntentionInspectionQuickFixTest.java index 3381bec67ed7f..f1d7457625e91 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/EmptyIntentionInspectionQuickFixTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/EmptyIntentionInspectionQuickFixTest.java @@ -4,6 +4,7 @@ import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.codeInspection.ProblemsHolder; +import com.intellij.codeInspection.defUse.DefUseInspection; import com.intellij.psi.JavaElementVisitor; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiLiteralExpression; @@ -26,7 +27,7 @@ protected String getBasePath() { @Override protected LocalInspectionTool[] configureLocalInspectionTools() { - return new LocalInspectionTool[]{new LocalInspectionTool() { + return new LocalInspectionTool[]{new DefUseInspection(), new LocalInspectionTool() { @Override @Nls @NotNull @@ -74,4 +75,26 @@ public void testX() throws Exception { } assertEquals(1, emptyActions.size()); } + + public void testLowPriority() throws Exception { + configureByFile(getBasePath() + ""/LowPriority.java""); + List emptyActions = getAvailableActions(); + int i = 0; + for(;i < emptyActions.size(); i++) { + final IntentionAction intentionAction = emptyActions.get(i); + if (""Make 'i' not final"".equals(intentionAction.getText())) { + break; + } + if (intentionAction instanceof EmptyIntentionAction) { + fail(""Low priority action prior to quick fix""); + } + } + assertTrue(i < emptyActions.size()); + for (; i < emptyActions.size(); i++) { + if (emptyActions.get(i) instanceof EmptyIntentionAction) { + return; + } + } + fail(""Missed inspection setting action""); + } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/EmptyIntentionAction.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/EmptyIntentionAction.java index 8808e65288f17..f74376b27b1d0 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/EmptyIntentionAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/EmptyIntentionAction.java @@ -29,7 +29,7 @@ * User: anna * Date: May 11, 2005 */ -public final class EmptyIntentionAction implements IntentionAction{ +public final class EmptyIntentionAction implements IntentionAction, LowPriorityAction{ private final String myName; public EmptyIntentionAction(@NotNull String name) {" ac93bc54a2c1a7b17d3a0b57fc9a24ec9d334c78,Delta Spike,"DELTASPIKE-289 WindowContext cleanup ",c,https://github.com/apache/deltaspike,"diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java index fbd585cdb..14663c5af 100644 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java @@ -30,7 +30,8 @@ * session as @SessionScoped bean. *

*

Every WindowContext is uniquely identified via a - * 'windowId'. Each Thread is associated with at most + * 'windowId' inside the current Session. + * Each Thread is associated with at most * one single windowId at a time. The {@link WindowContext} * is the interface which allows resolving the current windowId * associated with this very Thread.

@@ -47,21 +48,12 @@ public interface WindowContext * If no WindowContext exists with the very windowId we will create a new one. * @param windowId */ - void activateWindowContext(String windowId); + void activateWindow(String windowId); /** - * close the WindowContext with the currently activated windowId for the very Thread. + * close the WindowContext with the given windowId. * @return true if any did exist, false otherwise */ - boolean closeCurrentWindowContext(); - - - /** - * Close all WindowContexts which are managed by the WindowContextManager. - * This is necessary when the session gets closed down or the application closes. - * @return - */ - void destroy(); - + boolean closeWindow(String windowId); } diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/context/AbstractContext.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/context/AbstractContext.java index 583faf80c..e30931ca2 100644 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/context/AbstractContext.java +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/context/AbstractContext.java @@ -154,9 +154,11 @@ public void destroyAllActive() } /** - * destroys all the Contextual Instances in the specified ContextualStorage. + * Destroys all the Contextual Instances in the specified ContextualStorage. + * This is a static method to allow various holder objects to cleanup + * properly in @PreDestroy. */ - public void destroyAllActive(ContextualStorage storage) + public static void destroyAllActive(ContextualStorage storage) { Map> contextMap = storage.getStorage(); for (Map.Entry> entry : contextMap.entrySet()) diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java index d51342f41..8acd0e663 100644 --- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java +++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java @@ -18,12 +18,14 @@ */ package org.apache.deltaspike.core.impl.scope.window; +import javax.annotation.PreDestroy; import javax.enterprise.context.SessionScoped; import javax.enterprise.inject.spi.BeanManager; import java.io.Serializable; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import org.apache.deltaspike.core.util.context.AbstractContext; import org.apache.deltaspike.core.util.context.ContextualStorage; /** @@ -41,6 +43,7 @@ public class WindowBeanHolder implements Serializable */ private volatile Map storageMap = new ConcurrentHashMap(); + //X TODO review usage public Map getStorageMap() { return storageMap; @@ -86,4 +89,18 @@ public Map forceNewStorage() storageMap = new ConcurrentHashMap(); return oldStorageMap; } + + @PreDestroy + public void destroyBeans() + { + // we replace the old windowBeanHolder beans with a new storage Map + // an afterwards destroy the old Beans without having to care about any syncs. + Map oldWindowContextStorages = forceNewStorage(); + + for (ContextualStorage contextualStorage : oldWindowContextStorages.values()) + { + AbstractContext.destroyAllActive(contextualStorage); + } + + } } diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowContextImpl.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowContextImpl.java index f20d02fe1..e9aa32661 100644 --- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowContextImpl.java +++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowContextImpl.java @@ -23,8 +23,6 @@ import javax.enterprise.inject.spi.BeanManager; import java.lang.annotation.Annotation; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import org.apache.deltaspike.core.api.scope.WindowScoped; import org.apache.deltaspike.core.spi.scope.window.WindowContext; @@ -38,13 +36,18 @@ public class WindowContextImpl extends AbstractContext implements WindowContext { /** - * all the {@link WindowContext}s which are active in this very Session. + * Holds the currently active windowId of each Request */ - private Map windowContexts = new ConcurrentHashMap(); - private WindowIdHolder windowIdHolder; + + /** + * Contains the stored WindowScoped contextual instances. + */ private WindowBeanHolder windowBeanHolder; + /** + * needed for serialisation and passivationId + */ private BeanManager beanManager; @@ -55,8 +58,20 @@ public WindowContextImpl(BeanManager beanManager) this.beanManager = beanManager; } + /** + * We need to pass the session scoped windowbean holder and the + * requestscoped windowIdHolder in a later phase because + * getBeans is only allowed from AfterDeploymentValidation onwards. + */ + void initWindowContext(WindowBeanHolder windowBeanHolder, WindowIdHolder windowIdHolder) + { + this.windowBeanHolder = windowBeanHolder; + this.windowIdHolder = windowIdHolder; + } + + @Override - public void activateWindowContext(String windowId) + public void activateWindow(String windowId) { windowIdHolder.setWindowId(windowId); } @@ -68,16 +83,15 @@ public String getCurrentWindowId() } @Override - public boolean closeCurrentWindowContext() + public boolean closeWindow(String windowId) { - String windowId = windowIdHolder.getWindowId(); if (windowId == null) { return false; } - WindowContext windowContext = windowContexts.get(windowId); - if (windowContext == null) + ContextualStorage windowStorage = windowBeanHolder.getContextualStorage(beanManager, windowId); + if (windowStorage == null) { return false; } @@ -85,19 +99,6 @@ public boolean closeCurrentWindowContext() return true; } - @Override - public synchronized void destroy() - { - // we replace the old windowBeanHolder beans with a new storage Map - // an afterwards destroy the old Beans without having to care about any syncs. - Map oldWindowContextStorages = windowBeanHolder.forceNewStorage(); - - for (ContextualStorage contextualStorage : oldWindowContextStorages.values()) - { - destroyAllActive(contextualStorage); - } - } - @Override protected ContextualStorage getContextualStorage(boolean createIfNotExist) { @@ -127,9 +128,4 @@ public boolean isActive() return windowId != null; } - void initWindowContext(WindowBeanHolder windowBeanHolder, WindowIdHolder windowIdHolder) - { - this.windowBeanHolder = windowBeanHolder; - this.windowIdHolder = windowIdHolder; - } } diff --git a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/impl/scope/window/DefaultWindowContextTest.java b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/impl/scope/window/DefaultWindowContextTest.java index 68408fda5..39640b8d4 100644 --- a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/impl/scope/window/DefaultWindowContextTest.java +++ b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/impl/scope/window/DefaultWindowContextTest.java @@ -68,14 +68,14 @@ public void testWindowScoedBean() Assert.assertNotNull(someWindowScopedBean); { - windowContext.activateWindowContext(""window1""); + windowContext.activateWindow(""window1""); someWindowScopedBean.setValue(""Hans""); Assert.assertEquals(""Hans"", someWindowScopedBean.getValue()); } // now we switch it away to another 'window' { - windowContext.activateWindowContext(""window2""); + windowContext.activateWindow(""window2""); Assert.assertNull(someWindowScopedBean.getValue()); someWindowScopedBean.setValue(""Karl""); Assert.assertEquals(""Karl"", someWindowScopedBean.getValue()); @@ -83,7 +83,7 @@ public void testWindowScoedBean() // and now back to the first window { - windowContext.activateWindowContext(""window1""); + windowContext.activateWindow(""window1""); // which must still contain the old value Assert.assertEquals(""Hans"", someWindowScopedBean.getValue()); @@ -91,7 +91,7 @@ public void testWindowScoedBean() // and again back to the second window { - windowContext.activateWindowContext(""window2""); + windowContext.activateWindow(""window2""); // which must still contain the old value of the 2nd window Assert.assertEquals(""Karl"", someWindowScopedBean.getValue());" a035e9fd8a5bde10c26338d7b23f75dbf59f1352,drools,JBRULES-2121: JavaDialect isn't creating unique ids- - fixed name that is checked--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@26929 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-,c,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialect.java b/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialect.java index 8d9bf344fe1..e6a9f723ae8 100644 --- a/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialect.java +++ b/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialect.java @@ -721,7 +721,7 @@ public static String getUniqueLegalName(final String packageName, counter++; final String fileName = packageName.replaceAll( ""\\."", - ""/"" ) + newName + ""_"" + counter + ext; + ""/"" ) + ""/"" + newName + ""_"" + counter + ""."" + ext; //MVEL:test null to Fix failing test on org.drools.rule.builder.dialect.mvel.MVELConsequenceBuilderTest.testImperativeCodeError() exists = src != null && src.isAvailable( fileName );" 01e706466e561557d8591b3031cd85ae39b0559a,intellij-community,gradle: correctly set TestModuleProperties for- modules containing '-' in names (IDEA-151590)--,c,https://github.com/JetBrains/intellij-community,"diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleData.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleData.java index 4179681ab59ba..c2c06d2180435 100644 --- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleData.java +++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleData.java @@ -3,7 +3,6 @@ import com.intellij.ide.highlighter.ModuleFileType; import com.intellij.openapi.externalSystem.model.ProjectSystemId; import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil; -import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -58,7 +57,7 @@ protected ModuleData(@NotNull String id, @NotNull String internalName, @NotNull String moduleFileDirectoryPath, @NotNull String externalConfigPath) { - super(owner, externalName, FileUtil.sanitizeFileName(internalName)); + super(owner, externalName, internalName); myId = id; myModuleTypeId = typeId; myExternalConfigPath = externalConfigPath; diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java index 2a7f6b2eb6c25..9f67df07d6893 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java @@ -234,8 +234,8 @@ public DataNode createModule(@NotNull IdeaModule gradleModule, @NotN } @NotNull - public String getInternalModuleName(@NotNull IdeaModule gradleModule, @NotNull String sourceSetName) { - return gradleModule.getName() + ""_"" + sourceSetName; + private static String getInternalModuleName(@NotNull IdeaModule gradleModule, @NotNull String sourceSetName) { + return FileUtil.sanitizeFileName(gradleModule.getName() + ""_"" + sourceSetName); } @Override diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleMiscImportingTest.java b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleMiscImportingTest.java index c28a1745846c8..88c0cb575d438 100644 --- a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleMiscImportingTest.java +++ b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleMiscImportingTest.java @@ -59,6 +59,20 @@ public void testTestModuleProperties() throws Exception { assertSame(productionModule, testModuleProperties.getProductionModule()); } + @Test + public void testTestModulePropertiesForModuleWithHyphenInName() throws Exception { + createSettingsFile(""rootProject.name='my-project'""); + importProject( + ""apply plugin: 'java'"" + ); + + assertModules(""my-project"", ""my_project_main"", ""my_project_test""); + + final Module testModule = getModule(""my_project_test""); + TestModuleProperties testModuleProperties = TestModuleProperties.getInstance(testModule); + assertEquals(""my_project_main"", testModuleProperties.getProductionModuleName()); + } + @Test public void testInheritProjectJdkForModules() throws Exception { importProject(" 663575068c45608bfd45348ec98d1a26834cbb51,tapiji,"Cleans up build properties and plugin description files. Based on previous refactorings, build properties got out-of-sync with the plug-in content. This change also cleans warnings from `plugin.xml` files. (cherry picked from commit 9ae85d634223cec5c208e29c63b81c773fccf0be) ",p,https://github.com/tapiji/tapiji,"diff --git a/org.eclipse.babel.tapiji.tools.core.ui/build.properties b/org.eclipse.babel.tapiji.tools.core.ui/build.properties index 285b8bf4..f48d8dca 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/build.properties +++ b/org.eclipse.babel.tapiji.tools.core.ui/build.properties @@ -3,4 +3,10 @@ output.. = bin/ bin.includes = META-INF/,\ .,\ plugin.xml,\ - icons/ + icons/,\ + about.html,\ + bin/,\ + epl-v10.html +src.includes = icons/,\ + epl-v10.html,\ + about.html diff --git a/org.eclipse.babel.tapiji.tools.core/build.properties b/org.eclipse.babel.tapiji.tools.core/build.properties index 58be59e2..d9a05cb6 100644 --- a/org.eclipse.babel.tapiji.tools.core/build.properties +++ b/org.eclipse.babel.tapiji.tools.core/build.properties @@ -6,10 +6,8 @@ bin.includes = plugin.xml,\ about.html,\ epl-v10.html,\ bin/,\ - src/,\ resourcebundle.jar -src.includes = src/,\ - schema/,\ +src.includes = schema/,\ about.html,\ epl-v10.html jars.compile.order = .,\ diff --git a/org.eclipse.babel.tapiji.tools.java.ui/build.properties b/org.eclipse.babel.tapiji.tools.java.ui/build.properties index 5435750f..f28f57e2 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/build.properties +++ b/org.eclipse.babel.tapiji.tools.java.ui/build.properties @@ -3,6 +3,8 @@ output.. = bin/ bin.includes = META-INF/,\ .,\ plugin.xml,\ - epl-v10.html -src.includes = src/,\ - epl-v10.html + epl-v10.html,\ + about.html,\ + bin/ +src.includes = epl-v10.html,\ + about.html diff --git a/org.eclipse.babel.tapiji.tools.java.ui/plugin.xml b/org.eclipse.babel.tapiji.tools.java.ui/plugin.xml index ba577346..666fd7e0 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/plugin.xml +++ b/org.eclipse.babel.tapiji.tools.java.ui/plugin.xml @@ -3,9 +3,9 @@ - - + diff --git a/org.eclipse.babel.tapiji.tools.java/build.properties b/org.eclipse.babel.tapiji.tools.java/build.properties index e9863e28..8971f49e 100644 --- a/org.eclipse.babel.tapiji.tools.java/build.properties +++ b/org.eclipse.babel.tapiji.tools.java/build.properties @@ -2,4 +2,8 @@ source.. = src/ output.. = bin/ bin.includes = META-INF/,\ .,\ - plugin.xml + epl-v10.html,\ + about.html,\ + bin/ +src.includes = epl-v10.html,\ + about.html diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/build.properties b/org.eclipse.babel.tapiji.tools.rbmanager/build.properties index f176c838..030c8540 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/build.properties +++ b/org.eclipse.babel.tapiji.tools.rbmanager/build.properties @@ -2,9 +2,13 @@ source.. = src/ output.. = bin/ bin.includes = META-INF/,\ .,\ - plugin.xml,\ bin/,\ - icons/ + icons/,\ + epl-v10.html,\ + about.html,\ + plugin.xml src.includes = icons/,\ - src/,\ - bin/ \ No newline at end of file + bin/,\ + epl-v10.html,\ + about.html +" 3990e8b478b1d958479c173c74946e38360cfd17,hadoop,Merge r1503933 from trunk to branch-2 for YARN-513.- Create common proxy client for communicating with RM (Xuan Gong & Jian He via- bikas)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1503935 13f79535-47bb-0310-9956-ffa450edef68-,a,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 65d19bff9d839..4d6cb00b23eca 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -465,6 +465,9 @@ Release 2.1.0-beta - 2013-07-02 YARN-521. Augment AM - RM client module to be able to request containers only at specific locations (Sandy Ryza via bikas) + YARN-513. Create common proxy client for communicating with RM. (Xuan Gong + & Jian He via bikas) + OPTIMIZATIONS YARN-512. Log aggregation root directory check is more expensive than it diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java index 44c35c3d58b28..b14e65225200d 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java @@ -655,17 +655,17 @@ public class YarnConfiguration extends Configuration { public static final long DEFAULT_NM_PROCESS_KILL_WAIT_MS = 2000; - /** Max time to wait to establish a connection to RM when NM starts + /** Max time to wait to establish a connection to RM */ - public static final String RESOURCEMANAGER_CONNECT_WAIT_SECS = - NM_PREFIX + ""resourcemanager.connect.wait.secs""; - public static final int DEFAULT_RESOURCEMANAGER_CONNECT_WAIT_SECS = + public static final String RESOURCEMANAGER_CONNECT_MAX_WAIT_SECS = + RM_PREFIX + ""resourcemanager.connect.max.wait.secs""; + public static final int DEFAULT_RESOURCEMANAGER_CONNECT_MAX_WAIT_SECS = 15*60; - /** Time interval between each NM attempt to connect to RM + /** Time interval between each attempt to connect to RM */ public static final String RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS = - NM_PREFIX + ""resourcemanager.connect.retry_interval.secs""; + RM_PREFIX + ""resourcemanager.connect.retry_interval.secs""; public static final long DEFAULT_RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS = 30; diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/ClientRMProxy.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/ClientRMProxy.java new file mode 100644 index 0000000000000..f70b44ce3a8db --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/ClientRMProxy.java @@ -0,0 +1,65 @@ +/** +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* ""License""); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an ""AS IS"" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +package org.apache.hadoop.yarn.client; + +import java.io.IOException; +import java.net.InetSocketAddress; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.yarn.api.ApplicationClientProtocol; +import org.apache.hadoop.yarn.api.ApplicationMasterProtocol; +import org.apache.hadoop.yarn.conf.YarnConfiguration; +import org.apache.hadoop.yarn.server.api.ResourceManagerAdministrationProtocol; + +public class ClientRMProxy extends RMProxy{ + + private static final Log LOG = LogFactory.getLog(ClientRMProxy.class); + + public static T createRMProxy(final Configuration conf, + final Class protocol) throws IOException { + InetSocketAddress rmAddress = getRMAddress(conf, protocol); + return createRMProxy(conf, protocol, rmAddress); + } + + private static InetSocketAddress getRMAddress(Configuration conf, Class protocol) { + if (protocol == ApplicationClientProtocol.class) { + return conf.getSocketAddr(YarnConfiguration.RM_ADDRESS, + YarnConfiguration.DEFAULT_RM_ADDRESS, + YarnConfiguration.DEFAULT_RM_PORT); + } else if (protocol == ResourceManagerAdministrationProtocol.class) { + return conf.getSocketAddr( + YarnConfiguration.RM_ADMIN_ADDRESS, + YarnConfiguration.DEFAULT_RM_ADMIN_ADDRESS, + YarnConfiguration.DEFAULT_RM_ADMIN_PORT); + } else if (protocol == ApplicationMasterProtocol.class) { + return conf.getSocketAddr( + YarnConfiguration.RM_SCHEDULER_ADDRESS, + YarnConfiguration.DEFAULT_RM_SCHEDULER_ADDRESS, + YarnConfiguration.DEFAULT_RM_SCHEDULER_PORT); + } else { + String message = ""Unsupported protocol found when creating the proxy "" + + ""connection to ResourceManager: "" + + ((protocol != null) ? protocol.getClass().getName() : ""null""); + LOG.error(message); + throw new IllegalStateException(message); + } + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/YarnClient.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/YarnClient.java index e8dca61d32a0b..22d80c6e8d90b 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/YarnClient.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/YarnClient.java @@ -19,7 +19,6 @@ package org.apache.hadoop.yarn.client.api; import java.io.IOException; -import java.net.InetSocketAddress; import java.util.List; import java.util.Set; @@ -54,25 +53,6 @@ public static YarnClient createYarnClient() { return client; } - /** - * Create a new instance of YarnClient. - */ - @Public - public static YarnClient createYarnClient(InetSocketAddress rmAddress) { - YarnClient client = new YarnClientImpl(rmAddress); - return client; - } - - /** - * Create a new instance of YarnClient. - */ - @Public - public static YarnClient createYarnClient(String name, - InetSocketAddress rmAddress) { - YarnClient client = new YarnClientImpl(name, rmAddress); - return client; - } - @Private protected YarnClient(String name) { super(name); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/AMRMClientImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/AMRMClientImpl.java index 0f088a0604b6e..4119a0cb1de7e 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/AMRMClientImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/AMRMClientImpl.java @@ -19,8 +19,6 @@ package org.apache.hadoop.yarn.client.api.impl; import java.io.IOException; -import java.net.InetSocketAddress; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -42,7 +40,6 @@ import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ipc.RPC; -import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.ApplicationMasterProtocol; import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; @@ -56,16 +53,16 @@ import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; +import org.apache.hadoop.yarn.client.ClientRMProxy; import org.apache.hadoop.yarn.client.api.AMRMClient; +import org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest; import org.apache.hadoop.yarn.client.api.InvalidContainerRequestException; import org.apache.hadoop.yarn.client.api.NMTokenCache; -import org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; -import org.apache.hadoop.yarn.ipc.YarnRPC; import org.apache.hadoop.yarn.util.RackResolver; import com.google.common.annotations.VisibleForTesting; @@ -171,28 +168,11 @@ protected void serviceInit(Configuration conf) throws Exception { @Override protected void serviceStart() throws Exception { final YarnConfiguration conf = new YarnConfiguration(getConfig()); - final YarnRPC rpc = YarnRPC.create(conf); - final InetSocketAddress rmAddress = conf.getSocketAddr( - YarnConfiguration.RM_SCHEDULER_ADDRESS, - YarnConfiguration.DEFAULT_RM_SCHEDULER_ADDRESS, - YarnConfiguration.DEFAULT_RM_SCHEDULER_PORT); - - UserGroupInformation currentUser; try { - currentUser = UserGroupInformation.getCurrentUser(); + rmClient = ClientRMProxy.createRMProxy(conf, ApplicationMasterProtocol.class); } catch (IOException e) { throw new YarnRuntimeException(e); } - - // CurrentUser should already have AMToken loaded. - rmClient = currentUser.doAs(new PrivilegedAction() { - @Override - public ApplicationMasterProtocol run() { - return (ApplicationMasterProtocol) rpc.getProxy(ApplicationMasterProtocol.class, rmAddress, - conf); - } - }); - LOG.debug(""Connecting to ResourceManager at "" + rmAddress); super.serviceStart(); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java index b3b8bdf4316bb..4398359862b06 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java @@ -59,11 +59,12 @@ import org.apache.hadoop.yarn.api.records.Token; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.api.records.YarnClusterMetrics; +import org.apache.hadoop.yarn.client.ClientRMProxy; import org.apache.hadoop.yarn.client.api.YarnClient; import org.apache.hadoop.yarn.client.api.YarnClientApplication; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; -import org.apache.hadoop.yarn.ipc.YarnRPC; +import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.util.Records; import com.google.common.annotations.VisibleForTesting; @@ -81,16 +82,7 @@ public class YarnClientImpl extends YarnClient { private static final String ROOT = ""root""; public YarnClientImpl() { - this(null); - } - - public YarnClientImpl(InetSocketAddress rmAddress) { - this(YarnClientImpl.class.getName(), rmAddress); - } - - public YarnClientImpl(String name, InetSocketAddress rmAddress) { - super(name); - this.rmAddress = rmAddress; + super(YarnClientImpl.class.getName()); } private static InetSocketAddress getRmAddress(Configuration conf) { @@ -100,9 +92,7 @@ private static InetSocketAddress getRmAddress(Configuration conf) { @Override protected void serviceInit(Configuration conf) throws Exception { - if (this.rmAddress == null) { - this.rmAddress = getRmAddress(conf); - } + this.rmAddress = getRmAddress(conf); statePollIntervalMillis = conf.getLong( YarnConfiguration.YARN_CLIENT_APP_SUBMISSION_POLL_INTERVAL_MS, YarnConfiguration.DEFAULT_YARN_CLIENT_APP_SUBMISSION_POLL_INTERVAL_MS); @@ -111,12 +101,11 @@ protected void serviceInit(Configuration conf) throws Exception { @Override protected void serviceStart() throws Exception { - YarnRPC rpc = YarnRPC.create(getConfig()); - - this.rmClient = (ApplicationClientProtocol) rpc.getProxy( - ApplicationClientProtocol.class, rmAddress, getConfig()); - if (LOG.isDebugEnabled()) { - LOG.debug(""Connecting to ResourceManager at "" + rmAddress); + try { + rmClient = ClientRMProxy.createRMProxy(getConfig(), + ApplicationClientProtocol.class); + } catch (IOException e) { + throw new YarnRuntimeException(e); } super.serviceStart(); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/RMAdminCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/RMAdminCLI.java index 6426fe9dbc77e..11335c0d8f68d 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/RMAdminCLI.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/RMAdminCLI.java @@ -19,8 +19,6 @@ package org.apache.hadoop.yarn.client.cli; import java.io.IOException; -import java.net.InetSocketAddress; -import java.security.PrivilegedAction; import java.util.Arrays; import org.apache.hadoop.classification.InterfaceAudience.Private; @@ -31,11 +29,11 @@ import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; +import org.apache.hadoop.yarn.client.ClientRMProxy; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; -import org.apache.hadoop.yarn.ipc.YarnRPC; import org.apache.hadoop.yarn.server.api.ResourceManagerAdministrationProtocol; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshAdminAclsRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshNodesRequest; @@ -164,32 +162,10 @@ private static void printUsage(String cmd) { } } - private static UserGroupInformation getUGI(Configuration conf - ) throws IOException { - return UserGroupInformation.getCurrentUser(); - } - private ResourceManagerAdministrationProtocol createAdminProtocol() throws IOException { // Get the current configuration final YarnConfiguration conf = new YarnConfiguration(getConf()); - - // Create the client - final InetSocketAddress addr = conf.getSocketAddr( - YarnConfiguration.RM_ADMIN_ADDRESS, - YarnConfiguration.DEFAULT_RM_ADMIN_ADDRESS, - YarnConfiguration.DEFAULT_RM_ADMIN_PORT); - final YarnRPC rpc = YarnRPC.create(conf); - - ResourceManagerAdministrationProtocol adminProtocol = - getUGI(conf).doAs(new PrivilegedAction() { - @Override - public ResourceManagerAdministrationProtocol run() { - return (ResourceManagerAdministrationProtocol) rpc.getProxy(ResourceManagerAdministrationProtocol.class, - addr, conf); - } - }); - - return adminProtocol; + return ClientRMProxy.createRMProxy(conf, ResourceManagerAdministrationProtocol.class); } private int refreshQueues() throws IOException, YarnException { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/client/RMProxy.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/client/RMProxy.java new file mode 100644 index 0000000000000..e4493b5a469b9 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/client/RMProxy.java @@ -0,0 +1,125 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.yarn.client; + +import java.io.IOException; +import java.net.ConnectException; +import java.net.InetSocketAddress; +import java.security.PrivilegedAction; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.classification.InterfaceAudience; +import org.apache.hadoop.classification.InterfaceStability; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.io.retry.RetryPolicies; +import org.apache.hadoop.io.retry.RetryPolicy; +import org.apache.hadoop.io.retry.RetryProxy; +import org.apache.hadoop.security.UserGroupInformation; +import org.apache.hadoop.yarn.conf.YarnConfiguration; +import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; +import org.apache.hadoop.yarn.ipc.YarnRPC; + +@InterfaceAudience.Public +@InterfaceStability.Evolving +public class RMProxy { + + private static final Log LOG = LogFactory.getLog(RMProxy.class); + + @SuppressWarnings(""unchecked"") + public static T createRMProxy(final Configuration conf, + final Class protocol, InetSocketAddress rmAddress) throws IOException { + RetryPolicy retryPolicy = createRetryPolicy(conf); + T proxy = RMProxy.getProxy(conf, protocol, rmAddress); + LOG.info(""Connecting to ResourceManager at "" + rmAddress); + return (T) RetryProxy.create(protocol, proxy, retryPolicy); + } + + @SuppressWarnings(""unchecked"") + protected static T getProxy(final Configuration conf, + final Class protocol, final InetSocketAddress rmAddress) + throws IOException { + return (T) UserGroupInformation.getCurrentUser().doAs( + new PrivilegedAction() { + + @Override + public T run() { + return (T) YarnRPC.create(conf).getProxy(protocol, rmAddress, conf); + } + }); + } + + public static RetryPolicy createRetryPolicy(Configuration conf) { + long rmConnectWaitMS = + conf.getInt( + YarnConfiguration.RESOURCEMANAGER_CONNECT_MAX_WAIT_SECS, + YarnConfiguration.DEFAULT_RESOURCEMANAGER_CONNECT_MAX_WAIT_SECS) + * 1000; + long rmConnectionRetryIntervalMS = + conf.getLong( + YarnConfiguration.RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS, + YarnConfiguration + .DEFAULT_RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS) + * 1000; + + if (rmConnectionRetryIntervalMS < 0) { + throw new YarnRuntimeException(""Invalid Configuration. "" + + YarnConfiguration.RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS + + "" should not be negative.""); + } + + boolean waitForEver = (rmConnectWaitMS == -1000); + + if (waitForEver) { + return RetryPolicies.RETRY_FOREVER; + } else { + if (rmConnectWaitMS < 0) { + throw new YarnRuntimeException(""Invalid Configuration. "" + + YarnConfiguration.RESOURCEMANAGER_CONNECT_MAX_WAIT_SECS + + "" can be -1, but can not be other negative numbers""); + } + + // try connect once + if (rmConnectWaitMS < rmConnectionRetryIntervalMS) { + LOG.warn(YarnConfiguration.RESOURCEMANAGER_CONNECT_MAX_WAIT_SECS + + "" is smaller than "" + + YarnConfiguration.RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS + + "". Only try connect once.""); + rmConnectWaitMS = 0; + } + } + + RetryPolicy retryPolicy = + RetryPolicies.retryUpToMaximumTimeWithFixedSleep(rmConnectWaitMS, + rmConnectionRetryIntervalMS, + TimeUnit.MILLISECONDS); + + Map, RetryPolicy> exceptionToPolicyMap = + new HashMap, RetryPolicy>(); + exceptionToPolicyMap.put(ConnectException.class, retryPolicy); + //TO DO: after HADOOP-9576, IOException can be changed to EOFException + exceptionToPolicyMap.put(IOException.class, retryPolicy); + + return RetryPolicies.retryByException(RetryPolicies.TRY_ONCE_THEN_FAIL, + exceptionToPolicyMap); + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/ServerRMProxy.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/ServerRMProxy.java new file mode 100644 index 0000000000000..ef9154fde1b5f --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/ServerRMProxy.java @@ -0,0 +1,55 @@ +/** +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* ""License""); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an ""AS IS"" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +package org.apache.hadoop.yarn.server.api; + +import java.io.IOException; +import java.net.InetSocketAddress; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.yarn.client.RMProxy; +import org.apache.hadoop.yarn.conf.YarnConfiguration; + +public class ServerRMProxy extends RMProxy{ + + private static final Log LOG = LogFactory.getLog(ServerRMProxy.class); + + public static T createRMProxy(final Configuration conf, + final Class protocol) throws IOException { + InetSocketAddress rmAddress = getRMAddress(conf, protocol); + return createRMProxy(conf, protocol, rmAddress); + } + + private static InetSocketAddress getRMAddress(Configuration conf, Class protocol) { + if (protocol == ResourceTracker.class) { + return conf.getSocketAddr( + YarnConfiguration.RM_RESOURCE_TRACKER_ADDRESS, + YarnConfiguration.DEFAULT_RM_RESOURCE_TRACKER_ADDRESS, + YarnConfiguration.DEFAULT_RM_RESOURCE_TRACKER_PORT); + } + else { + String message = ""Unsupported protocol found when creating the proxy "" + + ""connection to ResourceManager: "" + + ((protocol != null) ? protocol.getClass().getName() : ""null""); + LOG.error(message); + throw new IllegalStateException(message); + } + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/impl/pb/client/ResourceTrackerPBClientImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/impl/pb/client/ResourceTrackerPBClientImpl.java index 396204cf2dbdb..40f6874623fdf 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/impl/pb/client/ResourceTrackerPBClientImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/impl/pb/client/ResourceTrackerPBClientImpl.java @@ -18,6 +18,7 @@ package org.apache.hadoop.yarn.server.api.impl.pb.client; +import java.io.Closeable; import java.io.IOException; import java.net.InetSocketAddress; @@ -41,7 +42,7 @@ import com.google.protobuf.ServiceException; -public class ResourceTrackerPBClientImpl implements ResourceTracker { +public class ResourceTrackerPBClientImpl implements ResourceTracker, Closeable { private ResourceTrackerPB proxy; @@ -50,7 +51,14 @@ public ResourceTrackerPBClientImpl(long clientVersion, InetSocketAddress addr, C proxy = (ResourceTrackerPB)RPC.getProxy( ResourceTrackerPB.class, clientVersion, addr, conf); } - + + @Override + public void close() { + if(this.proxy != null) { + RPC.stopProxy(this.proxy); + } + } + @Override public RegisterNodeManagerResponse registerNodeManager( RegisterNodeManagerRequest request) throws YarnException, diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeStatusUpdaterImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeStatusUpdaterImpl.java index 550cdc5a98f4f..b0e71e915633e 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeStatusUpdaterImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeStatusUpdaterImpl.java @@ -19,7 +19,7 @@ package org.apache.hadoop.yarn.server.nodemanager; import java.io.IOException; -import java.net.InetSocketAddress; +import java.net.ConnectException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -33,6 +33,7 @@ import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.service.AbstractService; import org.apache.hadoop.yarn.api.records.ApplicationId; @@ -47,9 +48,9 @@ import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; -import org.apache.hadoop.yarn.ipc.YarnRPC; import org.apache.hadoop.yarn.server.api.ResourceManagerConstants; import org.apache.hadoop.yarn.server.api.ResourceTracker; +import org.apache.hadoop.yarn.server.api.ServerRMProxy; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerRequest; @@ -77,7 +78,6 @@ public class NodeStatusUpdaterImpl extends AbstractService implements private NodeId nodeId; private long nextHeartBeatInterval; private ResourceTracker resourceTracker; - private InetSocketAddress rmAddress; private Resource totalResource; private int httpPort; private volatile boolean isStopped; @@ -91,9 +91,6 @@ public class NodeStatusUpdaterImpl extends AbstractService implements private final NodeHealthCheckerService healthChecker; private final NodeManagerMetrics metrics; - private long rmConnectWaitMS; - private long rmConnectionRetryIntervalMS; - private boolean waitForEver; private Runnable statusUpdaterRunnable; private Thread statusUpdater; @@ -110,11 +107,6 @@ public NodeStatusUpdaterImpl(Context context, Dispatcher dispatcher, @Override protected void serviceInit(Configuration conf) throws Exception { - this.rmAddress = conf.getSocketAddr( - YarnConfiguration.RM_RESOURCE_TRACKER_ADDRESS, - YarnConfiguration.DEFAULT_RM_RESOURCE_TRACKER_ADDRESS, - YarnConfiguration.DEFAULT_RM_RESOURCE_TRACKER_PORT); - int memoryMb = conf.getInt( YarnConfiguration.NM_PMEM_MB, YarnConfiguration.DEFAULT_NM_PMEM_MB); @@ -153,6 +145,7 @@ protected void serviceStart() throws Exception { try { // Registration has to be in start so that ContainerManager can get the // perNM tokens needed to authenticate ContainerTokens. + this.resourceTracker = getRMClient(); registerWithRM(); super.serviceStart(); startStatusUpdater(); @@ -167,6 +160,7 @@ protected void serviceStart() throws Exception { protected void serviceStop() throws Exception { // Interrupt the updater. this.isStopped = true; + stopRMProxy(); super.serviceStop(); } @@ -188,6 +182,13 @@ protected void rebootNodeStatusUpdater() { } } + @VisibleForTesting + protected void stopRMProxy() { + if(this.resourceTracker != null) { + RPC.stopProxy(this.resourceTracker); + } + } + @Private protected boolean isTokenKeepAliveEnabled(Configuration conf) { return conf.getBoolean(YarnConfiguration.LOG_AGGREGATION_ENABLED, @@ -195,93 +196,22 @@ protected boolean isTokenKeepAliveEnabled(Configuration conf) { && UserGroupInformation.isSecurityEnabled(); } - protected ResourceTracker getRMClient() { + @VisibleForTesting + protected ResourceTracker getRMClient() throws IOException { Configuration conf = getConfig(); - YarnRPC rpc = YarnRPC.create(conf); - return (ResourceTracker) rpc.getProxy(ResourceTracker.class, rmAddress, - conf); + return ServerRMProxy.createRMProxy(conf, ResourceTracker.class); } @VisibleForTesting protected void registerWithRM() throws YarnException, IOException { - Configuration conf = getConfig(); - rmConnectWaitMS = - conf.getInt( - YarnConfiguration.RESOURCEMANAGER_CONNECT_WAIT_SECS, - YarnConfiguration.DEFAULT_RESOURCEMANAGER_CONNECT_WAIT_SECS) - * 1000; - rmConnectionRetryIntervalMS = - conf.getLong( - YarnConfiguration.RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS, - YarnConfiguration - .DEFAULT_RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS) - * 1000; - - if(rmConnectionRetryIntervalMS < 0) { - throw new YarnRuntimeException(""Invalid Configuration. "" + - YarnConfiguration.RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS + - "" should not be negative.""); - } - - waitForEver = (rmConnectWaitMS == -1000); - - if(! waitForEver) { - if(rmConnectWaitMS < 0) { - throw new YarnRuntimeException(""Invalid Configuration. "" + - YarnConfiguration.RESOURCEMANAGER_CONNECT_WAIT_SECS + - "" can be -1, but can not be other negative numbers""); - } - - //try connect once - if(rmConnectWaitMS < rmConnectionRetryIntervalMS) { - LOG.warn(YarnConfiguration.RESOURCEMANAGER_CONNECT_WAIT_SECS - + "" is smaller than "" - + YarnConfiguration.RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS - + "". Only try connect once.""); - rmConnectWaitMS = 0; - } - } - - int rmRetryCount = 0; - long waitStartTime = System.currentTimeMillis(); - RegisterNodeManagerRequest request = recordFactory.newRecordInstance(RegisterNodeManagerRequest.class); request.setHttpPort(this.httpPort); request.setResource(this.totalResource); request.setNodeId(this.nodeId); - RegisterNodeManagerResponse regNMResponse; - - while(true) { - try { - rmRetryCount++; - LOG.info(""Connecting to ResourceManager at "" + this.rmAddress - + "". current no. of attempts is "" + rmRetryCount); - this.resourceTracker = getRMClient(); - regNMResponse = - this.resourceTracker.registerNodeManager(request); - this.rmIdentifier = regNMResponse.getRMIdentifier(); - break; - } catch(Throwable e) { - LOG.warn(""Trying to connect to ResourceManager, "" + - ""current no. of failed attempts is ""+rmRetryCount); - if(System.currentTimeMillis() - waitStartTime < rmConnectWaitMS - || waitForEver) { - try { - LOG.info(""Sleeping for "" + rmConnectionRetryIntervalMS/1000 - + "" seconds before next connection retry to RM""); - Thread.sleep(rmConnectionRetryIntervalMS); - } catch(InterruptedException ex) { - //done nothing - } - } else { - String errorMessage = ""Failed to Connect to RM, "" + - ""no. of failed attempts is ""+rmRetryCount; - LOG.error(errorMessage,e); - throw new YarnRuntimeException(errorMessage,e); - } - } - } + RegisterNodeManagerResponse regNMResponse = + resourceTracker.registerNodeManager(request); + this.rmIdentifier = regNMResponse.getRMIdentifier(); // if the Resourcemanager instructs NM to shutdown. if (NodeAction.SHUTDOWN.equals(regNMResponse.getNodeAction())) { String message = @@ -426,8 +356,6 @@ public void run() { // Send heartbeat try { NodeHeartbeatResponse response = null; - int rmRetryCount = 0; - long waitStartTime = System.currentTimeMillis(); NodeStatus nodeStatus = getNodeStatusAndUpdateContainersInContext(); nodeStatus.setResponseId(lastHeartBeatID); @@ -440,31 +368,7 @@ public void run() { request .setLastKnownNMTokenMasterKey(NodeStatusUpdaterImpl.this.context .getNMTokenSecretManager().getCurrentKey()); - while (!isStopped) { - try { - rmRetryCount++; - response = resourceTracker.nodeHeartbeat(request); - break; - } catch (Throwable e) { - LOG.warn(""Trying to heartbeat to ResourceManager, "" - + ""current no. of failed attempts is "" + rmRetryCount); - if(System.currentTimeMillis() - waitStartTime < rmConnectWaitMS - || waitForEver) { - try { - LOG.info(""Sleeping for "" + rmConnectionRetryIntervalMS/1000 - + "" seconds before next heartbeat to RM""); - Thread.sleep(rmConnectionRetryIntervalMS); - } catch(InterruptedException ex) { - //done nothing - } - } else { - String errorMessage = ""Failed to heartbeat to RM, "" + - ""no. of failed attempts is ""+rmRetryCount; - LOG.error(errorMessage,e); - throw new YarnRuntimeException(errorMessage,e); - } - } - } + response = resourceTracker.nodeHeartbeat(request); //get next heartbeat interval from response nextHeartBeatInterval = response.getNextHeartBeatInterval(); updateMasterKeys(response); @@ -508,11 +412,11 @@ public void run() { dispatcher.getEventHandler().handle( new CMgrCompletedAppsEvent(appsToCleanup)); } - } catch (YarnRuntimeException e) { + } catch (ConnectException e) { //catch and throw the exception if tried MAX wait time to connect RM dispatcher.getEventHandler().handle( new NodeManagerEvent(NodeManagerEventType.SHUTDOWN)); - throw e; + throw new YarnRuntimeException(e); } catch (Throwable e) { // TODO Better error handling. Thread can die with the rest of the // NM still running. diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/MockNodeStatusUpdater.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/MockNodeStatusUpdater.java index e93778e2987ef..a3e1faf310e54 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/MockNodeStatusUpdater.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/MockNodeStatusUpdater.java @@ -61,6 +61,10 @@ public MockNodeStatusUpdater(Context context, Dispatcher dispatcher, protected ResourceTracker getRMClient() { return resourceTracker; } + @Override + protected void stopRMProxy() { + return; + } private static class MockResourceTracker implements ResourceTracker { private int heartBeatID; diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java index 668b85b6511bd..294c93ed3b84a 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java @@ -107,6 +107,11 @@ protected ResourceTracker getRMClient() { return new LocalRMInterface(); }; + @Override + protected void stopRMProxy() { + return; + } + @Override protected void startStatusUpdater() { return; // Don't start any updating thread. diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java index e17131fd3a1dc..2a3e3d579ca03 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java @@ -41,6 +41,8 @@ import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.Path; +import org.apache.hadoop.io.retry.RetryPolicy; +import org.apache.hadoop.io.retry.RetryProxy; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.service.ServiceOperations; @@ -53,6 +55,7 @@ import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Resource; +import org.apache.hadoop.yarn.client.RMProxy; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.event.EventHandler; @@ -60,9 +63,9 @@ import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; -import org.apache.hadoop.yarn.ipc.RPCUtil; import org.apache.hadoop.yarn.security.ContainerTokenIdentifier; import org.apache.hadoop.yarn.server.api.ResourceTracker; +import org.apache.hadoop.yarn.server.api.ServerRMProxy; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerRequest; @@ -103,11 +106,17 @@ public class TestNodeStatusUpdater { volatile int heartBeatID = 0; volatile Throwable nmStartError = null; private final List registeredNodes = new ArrayList(); - private final Configuration conf = createNMConfig(); + private boolean triggered = false; + private Configuration conf; private NodeManager nm; private boolean containerStatusBackupSuccessfully = true; private List completedContainerStatusList = new ArrayList(); + @Before + public void setUp() { + conf = createNMConfig(); + } + @After public void tearDown() { this.registeredNodes.clear(); @@ -274,6 +283,11 @@ public MyNodeStatusUpdater(Context context, Dispatcher dispatcher, protected ResourceTracker getRMClient() { return resourceTracker; } + + @Override + protected void stopRMProxy() { + return; + } } private class MyNodeStatusUpdater2 extends NodeStatusUpdaterImpl { @@ -290,6 +304,10 @@ protected ResourceTracker getRMClient() { return resourceTracker; } + @Override + protected void stopRMProxy() { + return; + } } private class MyNodeStatusUpdater3 extends NodeStatusUpdaterImpl { @@ -307,7 +325,12 @@ public MyNodeStatusUpdater3(Context context, Dispatcher dispatcher, protected ResourceTracker getRMClient() { return resourceTracker; } - + + @Override + protected void stopRMProxy() { + return; + } + @Override protected boolean isTokenKeepAliveEnabled(Configuration conf) { return true; @@ -315,21 +338,16 @@ protected boolean isTokenKeepAliveEnabled(Configuration conf) { } private class MyNodeStatusUpdater4 extends NodeStatusUpdaterImpl { - public ResourceTracker resourceTracker = - new MyResourceTracker(this.context); + private Context context; - private long waitStartTime; private final long rmStartIntervalMS; private final boolean rmNeverStart; - private volatile boolean triggered = false; - private long durationWhenTriggered = -1; - + public ResourceTracker resourceTracker; public MyNodeStatusUpdater4(Context context, Dispatcher dispatcher, NodeHealthCheckerService healthChecker, NodeManagerMetrics metrics, long rmStartIntervalMS, boolean rmNeverStart) { super(context, dispatcher, healthChecker, metrics); this.context = context; - this.waitStartTime = System.currentTimeMillis(); this.rmStartIntervalMS = rmStartIntervalMS; this.rmNeverStart = rmNeverStart; } @@ -337,25 +355,16 @@ public MyNodeStatusUpdater4(Context context, Dispatcher dispatcher, @Override protected void serviceStart() throws Exception { //record the startup time - this.waitStartTime = System.currentTimeMillis(); super.serviceStart(); } @Override - protected ResourceTracker getRMClient() { - if (!triggered) { - long t = System.currentTimeMillis(); - long duration = t - waitStartTime; - if (duration <= rmStartIntervalMS - || rmNeverStart) { - throw new YarnRuntimeException(""Faking RM start failure as start "" + - ""delay timer has not expired.""); - } else { - //triggering - triggered = true; - durationWhenTriggered = duration; - } - } + protected ResourceTracker getRMClient() throws IOException { + RetryPolicy retryPolicy = RMProxy.createRetryPolicy(conf); + resourceTracker = + (ResourceTracker) RetryProxy.create(ResourceTracker.class, + new MyResourceTracker6(this.context, rmStartIntervalMS, + rmNeverStart), retryPolicy); return resourceTracker; } @@ -363,37 +372,35 @@ private boolean isTriggered() { return triggered; } - private long getWaitStartTime() { - return waitStartTime; - } - - private long getDurationWhenTriggered() { - return durationWhenTriggered; - } - @Override - public String toString() { - return ""MyNodeStatusUpdater4{"" + - ""rmNeverStart="" + rmNeverStart + - "", triggered="" + triggered + - "", duration="" + durationWhenTriggered + - "", rmStartIntervalMS="" + rmStartIntervalMS + - '}'; + protected void stopRMProxy() { + return; } } + + private class MyNodeStatusUpdater5 extends NodeStatusUpdaterImpl { private ResourceTracker resourceTracker; + private Configuration conf; public MyNodeStatusUpdater5(Context context, Dispatcher dispatcher, - NodeHealthCheckerService healthChecker, NodeManagerMetrics metrics) { + NodeHealthCheckerService healthChecker, NodeManagerMetrics metrics, Configuration conf) { super(context, dispatcher, healthChecker, metrics); resourceTracker = new MyResourceTracker5(); + this.conf = conf; } @Override protected ResourceTracker getRMClient() { - return resourceTracker; + RetryPolicy retryPolicy = RMProxy.createRetryPolicy(conf); + return (ResourceTracker) RetryProxy.create(ResourceTracker.class, + resourceTracker, retryPolicy); + } + + @Override + protected void stopRMProxy() { + return; } } @@ -417,15 +424,18 @@ private class MyNodeManager2 extends NodeManager { public boolean isStopped = false; private NodeStatusUpdater nodeStatusUpdater; private CyclicBarrier syncBarrier; - public MyNodeManager2 (CyclicBarrier syncBarrier) { + private Configuration conf; + + public MyNodeManager2 (CyclicBarrier syncBarrier, Configuration conf) { this.syncBarrier = syncBarrier; + this.conf = conf; } @Override protected NodeStatusUpdater createNodeStatusUpdater(Context context, Dispatcher dispatcher, NodeHealthCheckerService healthChecker) { nodeStatusUpdater = new MyNodeStatusUpdater5(context, dispatcher, healthChecker, - metrics); + metrics, conf); return nodeStatusUpdater; } @@ -577,7 +587,7 @@ public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request) .get(4).getState() == ContainerState.RUNNING && request.getNodeStatus().getContainersStatuses().get(4) .getContainerId().getId() == 5); - throw new YarnRuntimeException(""Lost the heartbeat response""); + throw new java.net.ConnectException(""Lost the heartbeat response""); } else if (heartBeatID == 2) { Assert.assertEquals(request.getNodeStatus().getContainersStatuses() .size(), 7); @@ -646,7 +656,63 @@ public RegisterNodeManagerResponse registerNodeManager( public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request) throws YarnException, IOException { heartBeatID++; - throw RPCUtil.getRemoteException(""NodeHeartbeat exception""); + throw new java.net.ConnectException( + ""NodeHeartbeat exception""); + } + } + + private class MyResourceTracker6 implements ResourceTracker { + + private final Context context; + private long rmStartIntervalMS; + private boolean rmNeverStart; + private final long waitStartTime; + + public MyResourceTracker6(Context context, long rmStartIntervalMS, + boolean rmNeverStart) { + this.context = context; + this.rmStartIntervalMS = rmStartIntervalMS; + this.rmNeverStart = rmNeverStart; + this.waitStartTime = System.currentTimeMillis(); + } + + @Override + public RegisterNodeManagerResponse registerNodeManager( + RegisterNodeManagerRequest request) throws YarnException, IOException, + IOException { + if (System.currentTimeMillis() - waitStartTime <= rmStartIntervalMS + || rmNeverStart) { + throw new java.net.ConnectException(""Faking RM start failure as start "" + + ""delay timer has not expired.""); + } else { + NodeId nodeId = request.getNodeId(); + Resource resource = request.getResource(); + LOG.info(""Registering "" + nodeId.toString()); + // NOTE: this really should be checking against the config value + InetSocketAddress expected = NetUtils.getConnectAddress( + conf.getSocketAddr(YarnConfiguration.NM_ADDRESS, null, -1)); + Assert.assertEquals(NetUtils.getHostPortString(expected), + nodeId.toString()); + Assert.assertEquals(5 * 1024, resource.getMemory()); + registeredNodes.add(nodeId); + + RegisterNodeManagerResponse response = recordFactory + .newRecordInstance(RegisterNodeManagerResponse.class); + triggered = true; + return response; + } + } + + @Override + public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request) + throws YarnException, IOException { + NodeStatus nodeStatus = request.getNodeStatus(); + nodeStatus.setResponseId(heartBeatID++); + + NodeHeartbeatResponse nhResponse = YarnServerBuilderUtils. + newNodeHeartbeatResponse(heartBeatID, NodeAction.NORMAL, null, + null, null, null, 1000L); + return nhResponse; } } @@ -843,8 +909,7 @@ public void testNMConnectionToRM() throws Exception { final long connectionRetryIntervalSecs = 1; //Waiting for rmStartIntervalMS, RM will be started final long rmStartIntervalMS = 2*1000; - YarnConfiguration conf = createNMConfig(); - conf.setLong(YarnConfiguration.RESOURCEMANAGER_CONNECT_WAIT_SECS, + conf.setLong(YarnConfiguration.RESOURCEMANAGER_CONNECT_MAX_WAIT_SECS, connectionWaitSecs); conf.setLong(YarnConfiguration .RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS, @@ -907,8 +972,6 @@ protected NodeStatusUpdater createUpdater(Context context, } long duration = System.currentTimeMillis() - waitStartTime; MyNodeStatusUpdater4 myUpdater = (MyNodeStatusUpdater4) updater; - Assert.assertTrue(""Updater was never started"", - myUpdater.getWaitStartTime()>0); Assert.assertTrue(""NM started before updater triggered"", myUpdater.isTriggered()); Assert.assertTrue(""NM should have connected to RM after "" @@ -1037,13 +1100,13 @@ public void testNodeStatusUpdaterRetryAndNMShutdown() final long connectionWaitSecs = 1; final long connectionRetryIntervalSecs = 1; YarnConfiguration conf = createNMConfig(); - conf.setLong(YarnConfiguration.RESOURCEMANAGER_CONNECT_WAIT_SECS, + conf.setLong(YarnConfiguration.RESOURCEMANAGER_CONNECT_MAX_WAIT_SECS, connectionWaitSecs); conf.setLong(YarnConfiguration .RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS, connectionRetryIntervalSecs); CyclicBarrier syncBarrier = new CyclicBarrier(2); - nm = new MyNodeManager2(syncBarrier); + nm = new MyNodeManager2(syncBarrier, conf); nm.init(conf); nm.start(); try { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java index 83d21e1640721..cfcf7f6445e63 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java @@ -117,6 +117,11 @@ protected ResourceTracker getRMClient() { return new LocalRMInterface(); }; + @Override + protected void stopRMProxy() { + return; + } + @Override protected void startStatusUpdater() { return; // Don't start any updating thread. diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java index cc529739dea79..144b111f83072 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java @@ -390,6 +390,11 @@ public RegisterNodeManagerResponse registerNodeManager( } }; }; + + @Override + protected void stopRMProxy() { + return; + } }; }; }" 83d5b1e6a0280cc78625bacc2d3f7d1676c7385e,kotlin,Supported propagation for subclass of- j.u.Collection and similar classes.--,a,https://github.com/JetBrains/kotlin,"diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaToKotlinMethodMap.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaToKotlinMethodMap.java new file mode 100644 index 0000000000000..cea6587792692 --- /dev/null +++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaToKotlinMethodMap.java @@ -0,0 +1,149 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.lang.resolve.java; + +import com.google.common.collect.*; +import com.intellij.openapi.util.Pair; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.util.PsiFormatUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.descriptors.ClassDescriptor; +import org.jetbrains.jet.lang.descriptors.FunctionDescriptor; +import org.jetbrains.jet.lang.resolve.DescriptorUtils; +import org.jetbrains.jet.lang.resolve.name.Name; +import org.jetbrains.jet.lang.types.JetType; +import org.jetbrains.jet.lang.types.TypeUtils; +import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns; +import org.jetbrains.jet.resolve.DescriptorRenderer; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class JavaToKotlinMethodMap { + public static final JavaToKotlinMethodMap INSTANCE = new JavaToKotlinMethodMap(); + + private final JavaToKotlinMethodMapGenerated mapContainer = new JavaToKotlinMethodMapGenerated(); + + private JavaToKotlinMethodMap() { + } + + @NotNull + private static Set getAllSuperClasses(@NotNull ClassDescriptor klass) { + Set allSupertypes = TypeUtils.getAllSupertypes(klass.getDefaultType()); + Set allSuperclasses = Sets.newHashSet(); + for (JetType supertype : allSupertypes) { + ClassDescriptor superclass = TypeUtils.getClassDescriptor(supertype); + assert superclass != null; + allSuperclasses.add(superclass); + } + return allSuperclasses; + } + + @NotNull + public List getFunctions(@NotNull PsiMethod psiMethod, @NotNull ClassDescriptor containingClass) { + ImmutableCollection classDatas = mapContainer.map.get(psiMethod.getContainingClass().getQualifiedName()); + + List result = Lists.newArrayList(); + + Set allSuperClasses = getAllSuperClasses(containingClass); + + String serializedPsiMethod = serializePsiMethod(psiMethod); + for (ClassData classData : classDatas) { + String expectedSerializedFunction = classData.method2Function.get(serializedPsiMethod); + if (expectedSerializedFunction == null) continue; + + ClassDescriptor kotlinClass = classData.kotlinClass; + if (!allSuperClasses.contains(kotlinClass)) continue; + + + Collection functions = + kotlinClass.getDefaultType().getMemberScope().getFunctions(Name.identifier(psiMethod.getName())); + + for (FunctionDescriptor function : functions) { + if (expectedSerializedFunction.equals(serializeFunction(function))) { + result.add(function); + } + } + } + + return result; + } + + @NotNull + public static String serializePsiMethod(@NotNull PsiMethod psiMethod) { + String externalName = PsiFormatUtil.getExternalName(psiMethod); + assert externalName != null : ""couldn't find external name for "" + psiMethod.getText(); + return externalName; + } + + @NotNull + public static String serializeFunction(@NotNull FunctionDescriptor fun) { + return DescriptorRenderer.TEXT.render(fun); + } + + // used in generated code + static Pair pair(String a, String b) { + return Pair.create(a, b); + } + + // used in generated code + static void put( + ImmutableMultimap.Builder builder, + String javaFqName, + String kotlinQualifiedName, + Pair... methods2Functions + ) { + ImmutableMap methods2FunctionsMap = pairs2Map(methods2Functions); + + ClassDescriptor kotlinClass; + if (kotlinQualifiedName.contains(""."")) { // Map.Entry and MutableMap.MutableEntry + String[] kotlinNames = kotlinQualifiedName.split(""\\.""); + assert kotlinNames.length == 2 : ""unexpected qualified name "" + kotlinQualifiedName; + + ClassDescriptor outerClass = KotlinBuiltIns.getInstance().getBuiltInClassByName(Name.identifier(kotlinNames[0])); + kotlinClass = DescriptorUtils.getInnerClassByName(outerClass, kotlinNames[1]); + assert kotlinClass != null : ""Class not found: "" + kotlinQualifiedName; + } + else { + kotlinClass = KotlinBuiltIns.getInstance().getBuiltInClassByName(Name.identifier(kotlinQualifiedName)); + } + + builder.put(javaFqName, new ClassData(kotlinClass, methods2FunctionsMap)); + } + + private static ImmutableMap pairs2Map(Pair[] pairs) { + ImmutableMap.Builder builder = ImmutableMap.builder(); + for (Pair pair : pairs) { + builder.put(pair.first, pair.second); + } + return builder.build(); + } + + static class ClassData { + @NotNull + public final ClassDescriptor kotlinClass; + @NotNull + public Map method2Function; + + public ClassData(@NotNull ClassDescriptor kotlinClass, @NotNull Map method2Function) { + this.kotlinClass = kotlinClass; + this.method2Function = method2Function; + } + } +} diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaToKotlinMethodMapGenerated.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaToKotlinMethodMapGenerated.java new file mode 100644 index 0000000000000..70de02d0f8a10 --- /dev/null +++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaToKotlinMethodMapGenerated.java @@ -0,0 +1,245 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.lang.resolve.java; + +import com.google.common.collect.ImmutableMultimap; + +import static org.jetbrains.jet.lang.resolve.java.JavaToKotlinMethodMap.*; + +/* This file is generated by org.jetbrains.jet.generators.GenerateJavaToKotlinMethodMap. DO NOT EDIT! */ +@SuppressWarnings(""unchecked"") +class JavaToKotlinMethodMapGenerated { + final ImmutableMultimap map; + + JavaToKotlinMethodMapGenerated() { + ImmutableMultimap.Builder b = ImmutableMultimap.builder(); + + put(b, ""java.lang.String"", ""String"", + pair(""java.lang.String int compareTo(java.lang.String)"", ""public open fun compareTo(that : jet.String) : jet.Int defined in jet.String""), + pair(""java.lang.String boolean equals(java.lang.Object)"", ""public final fun equals(other : jet.Any?) : jet.Boolean defined in jet.String""), + pair(""java.lang.String java.lang.String toString()"", ""public open fun toString() : jet.String defined in jet.String"") + ); + + put(b, ""java.lang.CharSequence"", ""CharSequence"", + pair(""java.lang.CharSequence java.lang.String toString()"", ""public abstract fun toString() : jet.String defined in jet.CharSequence"") + ); + + put(b, ""java.lang.Throwable"", ""Throwable"", + pair(""java.lang.Throwable java.lang.Throwable getCause()"", ""public final fun getCause() : jet.Throwable? defined in jet.Throwable""), + pair(""java.lang.Throwable java.lang.String getMessage()"", ""public final fun getMessage() : jet.String? defined in jet.Throwable""), + pair(""java.lang.Throwable void printStackTrace()"", ""public final fun printStackTrace() : Unit defined in jet.Throwable"") + ); + + put(b, ""java.lang.Comparable"", ""Comparable"", + pair(""java.lang.Comparable int compareTo(T)"", ""public abstract fun compareTo(other : T) : jet.Int defined in jet.Comparable"") + ); + + put(b, ""java.lang.Enum"", ""Enum"", + pair(""java.lang.Enum java.lang.String name()"", ""public final fun name() : jet.String defined in jet.Enum""), + pair(""java.lang.Enum int ordinal()"", ""public final fun ordinal() : jet.Int defined in jet.Enum"") + ); + + put(b, ""java.lang.Iterable"", ""Iterable"", + pair(""java.lang.Iterable java.util.Iterator iterator()"", ""public abstract fun iterator() : jet.Iterator defined in jet.Iterable"") + ); + + put(b, ""java.lang.Iterable"", ""MutableIterable"", + pair(""java.lang.Iterable java.util.Iterator iterator()"", ""public abstract fun iterator() : jet.MutableIterator defined in jet.MutableIterable"") + ); + + put(b, ""java.util.Iterator"", ""Iterator"", + pair(""java.util.Iterator boolean hasNext()"", ""public abstract fun hasNext() : jet.Boolean defined in jet.Iterator""), + pair(""java.util.Iterator E next()"", ""public abstract fun next() : T defined in jet.Iterator"") + ); + + put(b, ""java.util.Iterator"", ""MutableIterator"", + pair(""java.util.Iterator boolean hasNext()"", ""public abstract fun hasNext() : jet.Boolean defined in jet.MutableIterator""), + pair(""java.util.Iterator E next()"", ""public abstract fun next() : T defined in jet.MutableIterator""), + pair(""java.util.Iterator void remove()"", ""public abstract fun remove() : Unit defined in jet.MutableIterator"") + ); + + put(b, ""java.util.Collection"", ""Collection"", + pair(""java.util.Collection boolean contains(java.lang.Object)"", ""public abstract fun contains(o : jet.Any?) : jet.Boolean defined in jet.Collection""), + pair(""java.util.Collection boolean containsAll(java.util.Collection)"", ""public abstract fun containsAll(c : jet.Collection) : jet.Boolean defined in jet.Collection""), + pair(""java.util.Collection boolean equals(java.lang.Object)"", ""public abstract fun equals(other : jet.Any?) : jet.Boolean defined in jet.Collection""), + pair(""java.util.Collection int hashCode()"", ""public abstract fun hashCode() : jet.Int defined in jet.Collection""), + pair(""java.util.Collection boolean isEmpty()"", ""public abstract fun isEmpty() : jet.Boolean defined in jet.Collection""), + pair(""java.util.Collection java.util.Iterator iterator()"", ""public abstract fun iterator() : jet.Iterator defined in jet.Collection""), + pair(""java.util.Collection int size()"", ""public abstract fun size() : jet.Int defined in jet.Collection""), + pair(""java.util.Collection T[] toArray(T[])"", ""public abstract fun toArray(a : jet.Array) : jet.Array defined in jet.Collection""), + pair(""java.util.Collection java.lang.Object[] toArray()"", ""public abstract fun toArray() : jet.Array defined in jet.Collection"") + ); + + put(b, ""java.util.Collection"", ""MutableCollection"", + pair(""java.util.Collection boolean add(E)"", ""public abstract fun add(e : E) : jet.Boolean defined in jet.MutableCollection""), + pair(""java.util.Collection boolean addAll(java.util.Collection)"", ""public abstract fun addAll(c : jet.Collection) : jet.Boolean defined in jet.MutableCollection""), + pair(""java.util.Collection void clear()"", ""public abstract fun clear() : Unit defined in jet.MutableCollection""), + pair(""java.util.Collection boolean contains(java.lang.Object)"", ""public abstract fun contains(o : jet.Any?) : jet.Boolean defined in jet.MutableCollection""), + pair(""java.util.Collection boolean containsAll(java.util.Collection)"", ""public abstract fun containsAll(c : jet.Collection) : jet.Boolean defined in jet.MutableCollection""), + pair(""java.util.Collection boolean equals(java.lang.Object)"", ""public abstract fun equals(other : jet.Any?) : jet.Boolean defined in jet.MutableCollection""), + pair(""java.util.Collection int hashCode()"", ""public abstract fun hashCode() : jet.Int defined in jet.MutableCollection""), + pair(""java.util.Collection boolean isEmpty()"", ""public abstract fun isEmpty() : jet.Boolean defined in jet.MutableCollection""), + pair(""java.util.Collection java.util.Iterator iterator()"", ""public abstract fun iterator() : jet.MutableIterator defined in jet.MutableCollection""), + pair(""java.util.Collection boolean remove(java.lang.Object)"", ""public abstract fun remove(o : jet.Any?) : jet.Boolean defined in jet.MutableCollection""), + pair(""java.util.Collection boolean removeAll(java.util.Collection)"", ""public abstract fun removeAll(c : jet.Collection) : jet.Boolean defined in jet.MutableCollection""), + pair(""java.util.Collection boolean retainAll(java.util.Collection)"", ""public abstract fun retainAll(c : jet.Collection) : jet.Boolean defined in jet.MutableCollection""), + pair(""java.util.Collection int size()"", ""public abstract fun size() : jet.Int defined in jet.MutableCollection""), + pair(""java.util.Collection T[] toArray(T[])"", ""public abstract fun toArray(a : jet.Array) : jet.Array defined in jet.MutableCollection""), + pair(""java.util.Collection java.lang.Object[] toArray()"", ""public abstract fun toArray() : jet.Array defined in jet.MutableCollection"") + ); + + put(b, ""java.util.List"", ""List"", + pair(""java.util.List boolean contains(java.lang.Object)"", ""public abstract fun contains(o : jet.Any?) : jet.Boolean defined in jet.List""), + pair(""java.util.List boolean containsAll(java.util.Collection)"", ""public abstract fun containsAll(c : jet.Collection) : jet.Boolean defined in jet.List""), + pair(""java.util.List boolean equals(java.lang.Object)"", ""public abstract fun equals(other : jet.Any?) : jet.Boolean defined in jet.List""), + pair(""java.util.List E get(int)"", ""public abstract fun get(index : jet.Int) : E defined in jet.List""), + pair(""java.util.List int hashCode()"", ""public abstract fun hashCode() : jet.Int defined in jet.List""), + pair(""java.util.List int indexOf(java.lang.Object)"", ""public abstract fun indexOf(o : jet.Any?) : jet.Int defined in jet.List""), + pair(""java.util.List boolean isEmpty()"", ""public abstract fun isEmpty() : jet.Boolean defined in jet.List""), + pair(""java.util.List java.util.Iterator iterator()"", ""public abstract fun iterator() : jet.Iterator defined in jet.List""), + pair(""java.util.List int lastIndexOf(java.lang.Object)"", ""public abstract fun lastIndexOf(o : jet.Any?) : jet.Int defined in jet.List""), + pair(""java.util.List java.util.ListIterator listIterator()"", ""public abstract fun listIterator() : jet.ListIterator defined in jet.List""), + pair(""java.util.List java.util.ListIterator listIterator(int)"", ""public abstract fun listIterator(index : jet.Int) : jet.ListIterator defined in jet.List""), + pair(""java.util.List int size()"", ""public abstract fun size() : jet.Int defined in jet.List""), + pair(""java.util.List java.util.List subList(int, int)"", ""public abstract fun subList(fromIndex : jet.Int, toIndex : jet.Int) : jet.List defined in jet.List""), + pair(""java.util.List T[] toArray(T[])"", ""public abstract fun toArray(a : jet.Array) : jet.Array defined in jet.List""), + pair(""java.util.List java.lang.Object[] toArray()"", ""public abstract fun toArray() : jet.Array defined in jet.List"") + ); + + put(b, ""java.util.List"", ""MutableList"", + pair(""java.util.List boolean add(E)"", ""public abstract fun add(e : E) : jet.Boolean defined in jet.MutableList""), + pair(""java.util.List void add(int, E)"", ""public abstract fun add(index : jet.Int, element : E) : Unit defined in jet.MutableList""), + pair(""java.util.List boolean addAll(int, java.util.Collection)"", ""public abstract fun addAll(index : jet.Int, c : jet.Collection) : jet.Boolean defined in jet.MutableList""), + pair(""java.util.List boolean addAll(java.util.Collection)"", ""public abstract fun addAll(c : jet.Collection) : jet.Boolean defined in jet.MutableList""), + pair(""java.util.List void clear()"", ""public abstract fun clear() : Unit defined in jet.MutableList""), + pair(""java.util.List boolean contains(java.lang.Object)"", ""public abstract fun contains(o : jet.Any?) : jet.Boolean defined in jet.MutableList""), + pair(""java.util.List boolean containsAll(java.util.Collection)"", ""public abstract fun containsAll(c : jet.Collection) : jet.Boolean defined in jet.MutableList""), + pair(""java.util.List boolean equals(java.lang.Object)"", ""public abstract fun equals(other : jet.Any?) : jet.Boolean defined in jet.MutableList""), + pair(""java.util.List E get(int)"", ""public abstract fun get(index : jet.Int) : E defined in jet.MutableList""), + pair(""java.util.List int hashCode()"", ""public abstract fun hashCode() : jet.Int defined in jet.MutableList""), + pair(""java.util.List int indexOf(java.lang.Object)"", ""public abstract fun indexOf(o : jet.Any?) : jet.Int defined in jet.MutableList""), + pair(""java.util.List boolean isEmpty()"", ""public abstract fun isEmpty() : jet.Boolean defined in jet.MutableList""), + pair(""java.util.List java.util.Iterator iterator()"", ""public abstract fun iterator() : jet.Iterator defined in jet.MutableList""), + pair(""java.util.List int lastIndexOf(java.lang.Object)"", ""public abstract fun lastIndexOf(o : jet.Any?) : jet.Int defined in jet.MutableList""), + pair(""java.util.List java.util.ListIterator listIterator()"", ""public abstract fun listIterator() : jet.MutableListIterator defined in jet.MutableList""), + pair(""java.util.List java.util.ListIterator listIterator(int)"", ""public abstract fun listIterator(index : jet.Int) : jet.MutableListIterator defined in jet.MutableList""), + pair(""java.util.List E remove(int)"", ""public abstract fun remove(index : jet.Int) : E defined in jet.MutableList""), + pair(""java.util.List boolean remove(java.lang.Object)"", ""public abstract fun remove(o : jet.Any?) : jet.Boolean defined in jet.MutableList""), + pair(""java.util.List boolean removeAll(java.util.Collection)"", ""public abstract fun removeAll(c : jet.Collection) : jet.Boolean defined in jet.MutableList""), + pair(""java.util.List boolean retainAll(java.util.Collection)"", ""public abstract fun retainAll(c : jet.Collection) : jet.Boolean defined in jet.MutableList""), + pair(""java.util.List E set(int, E)"", ""public abstract fun set(index : jet.Int, element : E) : E defined in jet.MutableList""), + pair(""java.util.List int size()"", ""public abstract fun size() : jet.Int defined in jet.MutableList""), + pair(""java.util.List java.util.List subList(int, int)"", ""public abstract fun subList(fromIndex : jet.Int, toIndex : jet.Int) : jet.MutableList defined in jet.MutableList""), + pair(""java.util.List T[] toArray(T[])"", ""public abstract fun toArray(a : jet.Array) : jet.Array defined in jet.MutableList""), + pair(""java.util.List java.lang.Object[] toArray()"", ""public abstract fun toArray() : jet.Array defined in jet.MutableList"") + ); + + put(b, ""java.util.Set"", ""Set"", + pair(""java.util.Set boolean contains(java.lang.Object)"", ""public abstract fun contains(o : jet.Any?) : jet.Boolean defined in jet.Set""), + pair(""java.util.Set boolean containsAll(java.util.Collection)"", ""public abstract fun containsAll(c : jet.Collection) : jet.Boolean defined in jet.Set""), + pair(""java.util.Set boolean equals(java.lang.Object)"", ""public abstract fun equals(other : jet.Any?) : jet.Boolean defined in jet.Set""), + pair(""java.util.Set int hashCode()"", ""public abstract fun hashCode() : jet.Int defined in jet.Set""), + pair(""java.util.Set boolean isEmpty()"", ""public abstract fun isEmpty() : jet.Boolean defined in jet.Set""), + pair(""java.util.Set java.util.Iterator iterator()"", ""public abstract fun iterator() : jet.Iterator defined in jet.Set""), + pair(""java.util.Set int size()"", ""public abstract fun size() : jet.Int defined in jet.Set""), + pair(""java.util.Set T[] toArray(T[])"", ""public abstract fun toArray(a : jet.Array) : jet.Array defined in jet.Set""), + pair(""java.util.Set java.lang.Object[] toArray()"", ""public abstract fun toArray() : jet.Array defined in jet.Set"") + ); + + put(b, ""java.util.Set"", ""MutableSet"", + pair(""java.util.Set boolean add(E)"", ""public abstract fun add(e : E) : jet.Boolean defined in jet.MutableSet""), + pair(""java.util.Set boolean addAll(java.util.Collection)"", ""public abstract fun addAll(c : jet.Collection) : jet.Boolean defined in jet.MutableSet""), + pair(""java.util.Set void clear()"", ""public abstract fun clear() : Unit defined in jet.MutableSet""), + pair(""java.util.Set boolean contains(java.lang.Object)"", ""public abstract fun contains(o : jet.Any?) : jet.Boolean defined in jet.MutableSet""), + pair(""java.util.Set boolean containsAll(java.util.Collection)"", ""public abstract fun containsAll(c : jet.Collection) : jet.Boolean defined in jet.MutableSet""), + pair(""java.util.Set boolean equals(java.lang.Object)"", ""public abstract fun equals(other : jet.Any?) : jet.Boolean defined in jet.MutableSet""), + pair(""java.util.Set int hashCode()"", ""public abstract fun hashCode() : jet.Int defined in jet.MutableSet""), + pair(""java.util.Set boolean isEmpty()"", ""public abstract fun isEmpty() : jet.Boolean defined in jet.MutableSet""), + pair(""java.util.Set java.util.Iterator iterator()"", ""public abstract fun iterator() : jet.MutableIterator defined in jet.MutableSet""), + pair(""java.util.Set boolean remove(java.lang.Object)"", ""public abstract fun remove(o : jet.Any?) : jet.Boolean defined in jet.MutableSet""), + pair(""java.util.Set boolean removeAll(java.util.Collection)"", ""public abstract fun removeAll(c : jet.Collection) : jet.Boolean defined in jet.MutableSet""), + pair(""java.util.Set boolean retainAll(java.util.Collection)"", ""public abstract fun retainAll(c : jet.Collection) : jet.Boolean defined in jet.MutableSet""), + pair(""java.util.Set int size()"", ""public abstract fun size() : jet.Int defined in jet.MutableSet""), + pair(""java.util.Set T[] toArray(T[])"", ""public abstract fun toArray(a : jet.Array) : jet.Array defined in jet.MutableSet""), + pair(""java.util.Set java.lang.Object[] toArray()"", ""public abstract fun toArray() : jet.Array defined in jet.MutableSet"") + ); + + put(b, ""java.util.Map"", ""Map"", + pair(""java.util.Map boolean containsKey(java.lang.Object)"", ""public abstract fun containsKey(key : jet.Any?) : jet.Boolean defined in jet.Map""), + pair(""java.util.Map boolean containsValue(java.lang.Object)"", ""public abstract fun containsValue(value : jet.Any?) : jet.Boolean defined in jet.Map""), + pair(""java.util.Map java.util.Set> entrySet()"", ""public abstract fun entrySet() : jet.Set> defined in jet.Map""), + pair(""java.util.Map V get(java.lang.Object)"", ""public abstract fun get(key : jet.Any?) : V? defined in jet.Map""), + pair(""java.util.Map boolean isEmpty()"", ""public abstract fun isEmpty() : jet.Boolean defined in jet.Map""), + pair(""java.util.Map java.util.Set keySet()"", ""public abstract fun keySet() : jet.Set defined in jet.Map""), + pair(""java.util.Map int size()"", ""public abstract fun size() : jet.Int defined in jet.Map""), + pair(""java.util.Map java.util.Collection values()"", ""public abstract fun values() : jet.Collection defined in jet.Map"") + ); + + put(b, ""java.util.Map"", ""MutableMap"", + pair(""java.util.Map void clear()"", ""public abstract fun clear() : Unit defined in jet.MutableMap""), + pair(""java.util.Map boolean containsKey(java.lang.Object)"", ""public abstract fun containsKey(key : jet.Any?) : jet.Boolean defined in jet.MutableMap""), + pair(""java.util.Map boolean containsValue(java.lang.Object)"", ""public abstract fun containsValue(value : jet.Any?) : jet.Boolean defined in jet.MutableMap""), + pair(""java.util.Map java.util.Set> entrySet()"", ""public abstract fun entrySet() : jet.MutableSet> defined in jet.MutableMap""), + pair(""java.util.Map V get(java.lang.Object)"", ""public abstract fun get(key : jet.Any?) : V? defined in jet.MutableMap""), + pair(""java.util.Map boolean isEmpty()"", ""public abstract fun isEmpty() : jet.Boolean defined in jet.MutableMap""), + pair(""java.util.Map java.util.Set keySet()"", ""public abstract fun keySet() : jet.MutableSet defined in jet.MutableMap""), + pair(""java.util.Map V put(K, V)"", ""public abstract fun put(key : K, value : V) : V? defined in jet.MutableMap""), + pair(""java.util.Map void putAll(java.util.Map)"", ""public abstract fun putAll(m : jet.Map) : Unit defined in jet.MutableMap""), + pair(""java.util.Map V remove(java.lang.Object)"", ""public abstract fun remove(key : jet.Any?) : V? defined in jet.MutableMap""), + pair(""java.util.Map int size()"", ""public abstract fun size() : jet.Int defined in jet.MutableMap""), + pair(""java.util.Map java.util.Collection values()"", ""public abstract fun values() : jet.MutableCollection defined in jet.MutableMap"") + ); + + put(b, ""java.util.Map.Entry"", ""Map.Entry"", + pair(""java.util.Map.Entry boolean equals(java.lang.Object)"", ""public abstract fun equals(other : jet.Any?) : jet.Boolean defined in jet.Map.Entry""), + pair(""java.util.Map.Entry K getKey()"", ""public abstract fun getKey() : K defined in jet.Map.Entry""), + pair(""java.util.Map.Entry V getValue()"", ""public abstract fun getValue() : V defined in jet.Map.Entry""), + pair(""java.util.Map.Entry int hashCode()"", ""public abstract fun hashCode() : jet.Int defined in jet.Map.Entry"") + ); + + put(b, ""java.util.Map.Entry"", ""MutableMap.MutableEntry"", + pair(""java.util.Map.Entry boolean equals(java.lang.Object)"", ""public abstract fun equals(other : jet.Any?) : jet.Boolean defined in jet.MutableMap.MutableEntry""), + pair(""java.util.Map.Entry K getKey()"", ""public abstract fun getKey() : K defined in jet.MutableMap.MutableEntry""), + pair(""java.util.Map.Entry V getValue()"", ""public abstract fun getValue() : V defined in jet.MutableMap.MutableEntry""), + pair(""java.util.Map.Entry int hashCode()"", ""public abstract fun hashCode() : jet.Int defined in jet.MutableMap.MutableEntry""), + pair(""java.util.Map.Entry V setValue(V)"", ""public abstract fun setValue(value : V) : V defined in jet.MutableMap.MutableEntry"") + ); + + put(b, ""java.util.ListIterator"", ""ListIterator"", + pair(""java.util.ListIterator boolean hasNext()"", ""public abstract fun hasNext() : jet.Boolean defined in jet.ListIterator""), + pair(""java.util.ListIterator boolean hasPrevious()"", ""public abstract fun hasPrevious() : jet.Boolean defined in jet.ListIterator""), + pair(""java.util.ListIterator E next()"", ""public abstract fun next() : T defined in jet.ListIterator""), + pair(""java.util.ListIterator int nextIndex()"", ""public abstract fun nextIndex() : jet.Int defined in jet.ListIterator""), + pair(""java.util.ListIterator E previous()"", ""public abstract fun previous() : T defined in jet.ListIterator""), + pair(""java.util.ListIterator int previousIndex()"", ""public abstract fun previousIndex() : jet.Int defined in jet.ListIterator"") + ); + + put(b, ""java.util.ListIterator"", ""MutableListIterator"", + pair(""java.util.ListIterator void add(E)"", ""public abstract fun add(e : T) : Unit defined in jet.MutableListIterator""), + pair(""java.util.ListIterator boolean hasNext()"", ""public abstract fun hasNext() : jet.Boolean defined in jet.MutableListIterator""), + pair(""java.util.ListIterator boolean hasPrevious()"", ""public abstract fun hasPrevious() : jet.Boolean defined in jet.MutableListIterator""), + pair(""java.util.ListIterator E next()"", ""public abstract fun next() : T defined in jet.MutableListIterator""), + pair(""java.util.ListIterator int nextIndex()"", ""public abstract fun nextIndex() : jet.Int defined in jet.MutableListIterator""), + pair(""java.util.ListIterator E previous()"", ""public abstract fun previous() : T defined in jet.MutableListIterator""), + pair(""java.util.ListIterator int previousIndex()"", ""public abstract fun previousIndex() : jet.Int defined in jet.MutableListIterator""), + pair(""java.util.ListIterator void remove()"", ""public abstract fun remove() : Unit defined in jet.MutableListIterator""), + pair(""java.util.ListIterator void set(E)"", ""public abstract fun set(e : T) : Unit defined in jet.MutableListIterator"") + ); + + map = b.build(); + } +} diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/kotlinSignature/SignaturesPropagationData.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/kotlinSignature/SignaturesPropagationData.java index 4eecef9f415d4..238e5343ed568 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/kotlinSignature/SignaturesPropagationData.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/kotlinSignature/SignaturesPropagationData.java @@ -28,7 +28,10 @@ import org.jetbrains.jet.lang.resolve.BindingTrace; import org.jetbrains.jet.lang.resolve.java.CollectionClassMapping; import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver; +import org.jetbrains.jet.lang.resolve.java.JavaToKotlinClassMap; +import org.jetbrains.jet.lang.resolve.java.JavaToKotlinMethodMap; import org.jetbrains.jet.lang.resolve.java.wrapper.PsiMethodWrapper; +import org.jetbrains.jet.lang.resolve.name.FqName; import org.jetbrains.jet.lang.resolve.name.FqNameUnsafe; import org.jetbrains.jet.lang.resolve.scopes.JetScope; import org.jetbrains.jet.lang.types.*; @@ -50,13 +53,14 @@ public class SignaturesPropagationData { private final Map autoTypeParameterToModified; public SignaturesPropagationData( + @NotNull ClassDescriptor containingClass, @NotNull JetType autoReturnType, // type built by JavaTypeTransformer from Java signature and @NotNull annotations @NotNull JavaDescriptorResolver.ValueParameterDescriptors autoValueParameters, // descriptors built by parameters resolver @NotNull List autoTypeParameters, // descriptors built by signature resolver @NotNull PsiMethodWrapper method, @NotNull BindingTrace trace ) { - superFunctions = getSuperFunctionsForMethod(method, trace); + superFunctions = getSuperFunctionsForMethod(method, trace, containingClass); autoTypeParameterToModified = SignaturesUtil.recreateTypeParametersAndReturnMapping(autoTypeParameters); @@ -187,7 +191,8 @@ public JetType fun(FunctionDescriptor superFunction) { private static List getSuperFunctionsForMethod( @NotNull PsiMethodWrapper method, - @NotNull BindingTrace trace + @NotNull BindingTrace trace, + @NotNull ClassDescriptor containingClass ) { List superFunctions = Lists.newArrayList(); for (HierarchicalMethodSignature superSignature : method.getPsiMethod().getHierarchicalMethodSignature().getSuperSignatures()) { @@ -196,15 +201,22 @@ private static List getSuperFunctionsForMethod( superFunctions.add(((FunctionDescriptor) superFun)); } else { - // TODO assert is temporarily disabled - // It fails because of bug in IDEA on Mac: it adds invalid roots to JDK classpath and it leads to the problem that - // getHierarchicalMethodSignature() returns elements from invalid virtual files - - // Function descriptor can't be find iff superclass is java.lang.Collection or similar (translated to jet.* collections) - //assert !JavaToKotlinClassMap.getInstance().mapPlatformClass( - // new FqName(superSignature.getMethod().getContainingClass().getQualifiedName())).isEmpty(): - // ""Can't find super function for "" + method.getPsiMethod() + "" defined in "" - // + method.getPsiMethod().getContainingClass(); + String fqName = superSignature.getMethod().getContainingClass().getQualifiedName(); + assert fqName != null; + Collection platformClasses = JavaToKotlinClassMap.getInstance().mapPlatformClass(new FqName(fqName)); + if (platformClasses.isEmpty()) { + // TODO assert is temporarily disabled + // It fails because of bug in IDEA on Mac: it adds invalid roots to JDK classpath and it leads to the problem that + // getHierarchicalMethodSignature() returns elements from invalid virtual files + + //assert false : ""Can't find super function for "" + method.getPsiMethod() + + // "" defined in "" + method.getPsiMethod().getContainingClass() + } + else { + List funsFromMap = + JavaToKotlinMethodMap.INSTANCE.getFunctions(superSignature.getMethod(), containingClass); + superFunctions.addAll(funsFromMap); + } } } diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/resolver/JavaFunctionResolver.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/resolver/JavaFunctionResolver.java index fb1c73aca457c..a528a0577ec0c 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/resolver/JavaFunctionResolver.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/resolver/JavaFunctionResolver.java @@ -144,8 +144,8 @@ private SimpleFunctionDescriptor resolveMethodToFunctionDescriptor( List superFunctions; if (ownerDescriptor instanceof ClassDescriptor) { - SignaturesPropagationData signaturesPropagationData = - new SignaturesPropagationData(returnType, valueParameterDescriptors, methodTypeParameters, method, trace); + SignaturesPropagationData signaturesPropagationData = new SignaturesPropagationData( + (ClassDescriptor) ownerDescriptor, returnType, valueParameterDescriptors, methodTypeParameters, method, trace); superFunctions = signaturesPropagationData.getSuperFunctions(); returnType = signaturesPropagationData.getModifiedReturnType(); @@ -214,6 +214,9 @@ private static void checkFunctionsOverrideCorrectly( ((ClassDescriptor) functionDescriptor.getContainingDeclaration()).getDefaultType()); FunctionDescriptor superFunctionSubstituted = superFunction.substitute(substitutor); + assert superFunctionSubstituted != null : + ""Couldn't substitute super function: "" + superFunction + "", substitutor = "" + substitutor; + OverrideCompatibilityInfo.Result overridableResult = isOverridableBy(superFunctionSubstituted, functionDescriptor).getResult(); boolean paramsOk = overridableResult == OverrideCompatibilityInfo.Result.OVERRIDABLE; diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/types/lang/KotlinBuiltIns.java b/compiler/frontend/src/org/jetbrains/jet/lang/types/lang/KotlinBuiltIns.java index 75e97187252d0..c8d2153ce2534 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/types/lang/KotlinBuiltIns.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/types/lang/KotlinBuiltIns.java @@ -334,12 +334,17 @@ public JetScope getBuiltInsScope() { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @NotNull - private ClassDescriptor getBuiltInClassByName(@NotNull String simpleName) { - ClassifierDescriptor classifier = getBuiltInsScope().getClassifier(Name.identifier(simpleName)); + public ClassDescriptor getBuiltInClassByName(@NotNull Name simpleName) { + ClassifierDescriptor classifier = getBuiltInsScope().getClassifier(simpleName); assert classifier instanceof ClassDescriptor : ""Must be a class descriptor "" + simpleName + "", but was "" + classifier; return (ClassDescriptor) classifier; } + @NotNull + private ClassDescriptor getBuiltInClassByName(@NotNull String simpleName) { + return getBuiltInClassByName(Name.identifier(simpleName)); + } + // Special @NotNull diff --git a/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfCollection.java b/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfCollection.java new file mode 100644 index 0000000000000..d5e36c9d1635b --- /dev/null +++ b/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfCollection.java @@ -0,0 +1,8 @@ +package test; + +import java.util.*; + +public interface SubclassOfCollection extends Collection { + Iterator iterator(); + +} diff --git a/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfCollection.kt b/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfCollection.kt new file mode 100644 index 0000000000000..d4159b0dd5dc3 --- /dev/null +++ b/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfCollection.kt @@ -0,0 +1,5 @@ +package test + +public trait SubclassOfCollection: MutableCollection { + override fun iterator() : MutableIterator +} diff --git a/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfCollection.txt b/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfCollection.txt new file mode 100644 index 0000000000000..c5005631e02fd --- /dev/null +++ b/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfCollection.txt @@ -0,0 +1,17 @@ +namespace test + +public abstract trait test.SubclassOfCollection : jet.MutableCollection { + public abstract override /*1*/ /*fake_override*/ fun add(/*0*/ e: E): jet.Boolean + public abstract override /*1*/ /*fake_override*/ fun addAll(/*0*/ c: jet.Collection): jet.Boolean + public abstract override /*1*/ /*fake_override*/ fun clear(): jet.Tuple0 + public abstract override /*1*/ /*fake_override*/ fun contains(/*0*/ o: jet.Any?): jet.Boolean + public abstract override /*1*/ /*fake_override*/ fun containsAll(/*0*/ c: jet.Collection): jet.Boolean + public abstract override /*1*/ /*fake_override*/ fun isEmpty(): jet.Boolean + public abstract override /*1*/ fun iterator(): jet.MutableIterator + public abstract override /*1*/ /*fake_override*/ fun remove(/*0*/ o: jet.Any?): jet.Boolean + public abstract override /*1*/ /*fake_override*/ fun removeAll(/*0*/ c: jet.Collection): jet.Boolean + public abstract override /*1*/ /*fake_override*/ fun retainAll(/*0*/ c: jet.Collection): jet.Boolean + public abstract override /*1*/ /*fake_override*/ fun size(): jet.Int + public abstract override /*1*/ /*fake_override*/ fun toArray(): jet.Array + public abstract override /*1*/ /*fake_override*/ fun toArray(/*0*/ a: jet.Array): jet.Array +} diff --git a/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfMapEntry.java b/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfMapEntry.java new file mode 100644 index 0000000000000..0924783402ae3 --- /dev/null +++ b/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfMapEntry.java @@ -0,0 +1,7 @@ +package test; + +import java.util.*; + +public interface SubclassOfMapEntry extends Map.Entry { + V setValue(V v); +} diff --git a/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfMapEntry.kt b/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfMapEntry.kt new file mode 100644 index 0000000000000..73127c5cab896 --- /dev/null +++ b/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfMapEntry.kt @@ -0,0 +1,5 @@ +package test + +public trait SubclassOfMapEntry: MutableMap.MutableEntry { + override fun setValue(p0: V) : V +} diff --git a/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfMapEntry.txt b/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfMapEntry.txt new file mode 100644 index 0000000000000..0c728cfaf3dc9 --- /dev/null +++ b/compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfMapEntry.txt @@ -0,0 +1,7 @@ +namespace test + +public abstract trait test.SubclassOfMapEntry : jet.MutableMap.MutableEntry { + public abstract override /*1*/ /*fake_override*/ fun getKey(): K + public abstract override /*1*/ /*fake_override*/ fun getValue(): V + public abstract override /*1*/ fun setValue(/*0*/ p0: V): V +} diff --git a/compiler/testData/loadJava/modality/ModalityOfFakeOverrides.txt b/compiler/testData/loadJava/modality/ModalityOfFakeOverrides.txt index 0f79be88c2f99..aaf74fc13a53b 100644 --- a/compiler/testData/loadJava/modality/ModalityOfFakeOverrides.txt +++ b/compiler/testData/loadJava/modality/ModalityOfFakeOverrides.txt @@ -18,7 +18,7 @@ public open class test.ModalityOfFakeOverrides : java.util.AbstractList protected final override /*1*/ /*fake_override*/ var modCount: jet.Int public open override /*1*/ /*fake_override*/ fun remove(/*0*/ p0: jet.Any?): jet.Boolean - public open override /*1*/ /*fake_override*/ fun remove(/*0*/ p0: jet.Int): jet.String? + public open override /*1*/ /*fake_override*/ fun remove(/*0*/ p0: jet.Int): jet.String public open override /*1*/ /*fake_override*/ fun removeAll(/*0*/ p0: jet.Collection): jet.Boolean protected open override /*1*/ /*fake_override*/ fun removeRange(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): jet.Tuple0 public open override /*1*/ /*fake_override*/ fun retainAll(/*0*/ p0: jet.Collection): jet.Boolean diff --git a/compiler/tests/org/jetbrains/jet/jvm/compiler/LoadJavaTestGenerated.java b/compiler/tests/org/jetbrains/jet/jvm/compiler/LoadJavaTestGenerated.java index 09f489924fed1..cd3dd08bbb775 100644 --- a/compiler/tests/org/jetbrains/jet/jvm/compiler/LoadJavaTestGenerated.java +++ b/compiler/tests/org/jetbrains/jet/jvm/compiler/LoadJavaTestGenerated.java @@ -649,6 +649,16 @@ public void testSameProjectionKind() throws Exception { doTest(""compiler/testData/loadJava/kotlinSignature/propagation/return/SameProjectionKind.java""); } + @TestMetadata(""SubclassOfCollection.java"") + public void testSubclassOfCollection() throws Exception { + doTest(""compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfCollection.java""); + } + + @TestMetadata(""SubclassOfMapEntry.java"") + public void testSubclassOfMapEntry() throws Exception { + doTest(""compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfMapEntry.java""); + } + @TestMetadata(""TwoSuperclassesConflictingProjectionKinds.java"") public void testTwoSuperclassesConflictingProjectionKinds() throws Exception { doTest(""compiler/testData/loadJava/kotlinSignature/propagation/return/TwoSuperclassesConflictingProjectionKinds.java""); diff --git a/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/LazyResolveNamespaceComparingTestGenerated.java b/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/LazyResolveNamespaceComparingTestGenerated.java index c22111f4f4093..736054fa0d33d 100644 --- a/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/LazyResolveNamespaceComparingTestGenerated.java +++ b/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/LazyResolveNamespaceComparingTestGenerated.java @@ -1539,6 +1539,16 @@ public void testSameProjectionKind() throws Exception { doTestSinglePackage(""compiler/testData/loadJava/kotlinSignature/propagation/return/SameProjectionKind.kt""); } + @TestMetadata(""SubclassOfCollection.kt"") + public void testSubclassOfCollection() throws Exception { + doTestSinglePackage(""compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfCollection.kt""); + } + + @TestMetadata(""SubclassOfMapEntry.kt"") + public void testSubclassOfMapEntry() throws Exception { + doTestSinglePackage(""compiler/testData/loadJava/kotlinSignature/propagation/return/SubclassOfMapEntry.kt""); + } + @TestMetadata(""TwoSuperclassesConflictingProjectionKinds.kt"") public void testTwoSuperclassesConflictingProjectionKinds() throws Exception { doTestSinglePackage(""compiler/testData/loadJava/kotlinSignature/propagation/return/TwoSuperclassesConflictingProjectionKinds.kt""); diff --git a/generators/generators.iml b/generators/generators.iml index a02cc242438e9..06ad1f8bf7f10 100644 --- a/generators/generators.iml +++ b/generators/generators.iml @@ -14,6 +14,7 @@ + diff --git a/generators/org/jetbrains/jet/generators/GenerateJavaToKotlinMethodMap.java b/generators/org/jetbrains/jet/generators/GenerateJavaToKotlinMethodMap.java new file mode 100644 index 0000000000000..7cfbc1d08c962 --- /dev/null +++ b/generators/org/jetbrains/jet/generators/GenerateJavaToKotlinMethodMap.java @@ -0,0 +1,248 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.generators; + +import com.google.common.collect.Lists; +import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Pair; +import com.intellij.openapi.util.io.FileUtil; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.impl.file.impl.JavaFileManager; +import com.intellij.psi.search.GlobalSearchScope; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.CompileCompilerDependenciesTest; +import org.jetbrains.jet.ConfigurationKind; +import org.jetbrains.jet.TestJdkKind; +import org.jetbrains.jet.cli.jvm.compiler.CompileEnvironmentUtil; +import org.jetbrains.jet.cli.jvm.compiler.JetCoreEnvironment; +import org.jetbrains.jet.lang.descriptors.ClassDescriptor; +import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; +import org.jetbrains.jet.lang.descriptors.FunctionDescriptor; +import org.jetbrains.jet.lang.resolve.DescriptorUtils; +import org.jetbrains.jet.lang.resolve.java.JavaToKotlinClassMapBuilder; +import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns; +import org.jetbrains.jet.resolve.DescriptorRenderer; +import org.jetbrains.jet.utils.Printer; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import static org.jetbrains.jet.lang.resolve.java.JavaToKotlinMethodMap.serializeFunction; +import static org.jetbrains.jet.lang.resolve.java.JavaToKotlinMethodMap.serializePsiMethod; + +public class GenerateJavaToKotlinMethodMap { + + public static final String BUILTINS_FQNAME_PREFIX = KotlinBuiltIns.BUILT_INS_PACKAGE_FQ_NAME.getFqName() + "".""; + + public static void main(String[] args) throws IOException { + JetCoreEnvironment coreEnvironment = new JetCoreEnvironment( + CompileEnvironmentUtil.createMockDisposable(), + CompileCompilerDependenciesTest.compilerConfigurationForTests(ConfigurationKind.JDK_ONLY, TestJdkKind.FULL_JDK)); + + StringBuilder buf = new StringBuilder(); + Printer printer = new Printer(buf); + + printer.print(FileUtil.loadFile(new File(""injector-generator/copyright.txt""))) + .println() + .println(""package org.jetbrains.jet.lang.resolve.java;"") + .println() + .println(""import com.google.common.collect.ImmutableMultimap;"") + .println() + .println(""import static org.jetbrains.jet.lang.resolve.java.JavaToKotlinMethodMap.*;"") + .println() + .println(""/* This file is generated by "", GenerateJavaToKotlinMethodMap.class.getName(), "". DO NOT EDIT! */"") + .println(""@SuppressWarnings(\""unchecked\"")"") + .println(""class JavaToKotlinMethodMapGenerated {"").pushIndent() + .println(""final ImmutableMultimap map;"") + .println() + .println(""JavaToKotlinMethodMapGenerated() {"").pushIndent() + .println(""ImmutableMultimap.Builder b = ImmutableMultimap.builder();"") + .println(); + + MyMapBuilder builder = new MyMapBuilder(coreEnvironment.getProject()); + printer.printWithNoIndent(builder.toString()); + + printer.println(""map = b.build();""); + printer.popIndent().println(""}""); + printer.popIndent().println(""}""); + + //noinspection IOResourceOpenedButNotSafelyClosed + FileWriter out = + new FileWriter(""compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaToKotlinMethodMapGenerated.java""); + + out.write(buf.toString()); + out.close(); + } + + private static class MyMapBuilder extends JavaToKotlinClassMapBuilder { + private final Project project; + private final StringBuilder buf = new StringBuilder(); + private final Printer printer = new Printer(buf).pushIndent().pushIndent(); + + public MyMapBuilder(@NotNull Project project) { + this.project = project; + init(); + } + + @Override + protected void register(@NotNull Class javaClass, @NotNull ClassDescriptor kotlinDescriptor, @NotNull Direction direction) { + processClass(javaClass, kotlinDescriptor); + } + + @Override + protected void register(@NotNull Class javaClass, + @NotNull ClassDescriptor kotlinDescriptor, + @NotNull ClassDescriptor kotlinMutableDescriptor, + @NotNull Direction direction) { + processClass(javaClass, kotlinDescriptor); + processClass(javaClass, kotlinMutableDescriptor); + } + + private void processClass(@NotNull Class javaClass, @NotNull ClassDescriptor kotlinClass) { + JavaFileManager javaFileManager = ServiceManager.getService(project, JavaFileManager.class); + PsiClass psiClass = javaFileManager.findClass(javaClass.getCanonicalName(), GlobalSearchScope.allScope(project)); + assert psiClass != null; + + List> methods2Functions = getClassMethods2Functions(kotlinClass, psiClass); + if (!methods2Functions.isEmpty()) { + appendBeforeClass(kotlinClass, psiClass); + appendClass(methods2Functions); + appendAfterClass(); + } + } + + private static List> getClassMethods2Functions( + @NotNull ClassDescriptor kotlinClass, + @NotNull PsiClass psiClass + ) { + PsiMethod[] methods = psiClass.getMethods(); + + List> result = Lists.newArrayList(); + + for (DeclarationDescriptor member : kotlinClass.getDefaultType().getMemberScope().getAllDescriptors()) { + if (!(member instanceof FunctionDescriptor) || member.getContainingDeclaration() != kotlinClass) { + continue; + } + + FunctionDescriptor fun = (FunctionDescriptor) member; + PsiMethod foundMethod = findMethod(methods, fun); + if (foundMethod != null) { + result.add(Pair.create(foundMethod, fun)); + } + } + + Collections.sort(result, new Comparator>() { + @Override + public int compare(Pair pair1, Pair pair2) { + PsiMethod method1 = pair1.first; + PsiMethod method2 = pair2.first; + + String name1 = method1.getName(); + String name2 = method2.getName(); + if (!name1.equals(name2)) { + return name1.compareTo(name2); + } + + String serialized1 = serializePsiMethod(method1); + String serialized2 = serializePsiMethod(method2); + return serialized1.compareTo(serialized2); + } + }); + return result; + } + + private static boolean match(@NotNull PsiMethod method, @NotNull FunctionDescriptor fun) { + // Compare method an function by name and parameters count. For all methods except one (List.remove) it is enough. + // If this changes, there will be assertion error in findMethod() + if (method.getName().equals(fun.getName().getIdentifier()) + && method.getParameterList().getParametersCount() == fun.getValueParameters().size()) { + + // ""special case"": remove(Int) and remove(Any?) in MutableList + if (method.getName().equals(""remove"") && method.getContainingClass().getName().equals(""List"")) { + String psiType = method.getParameterList().getParameters()[0].getType().getPresentableText(); + String jetType = DescriptorRenderer.TEXT.renderTypeWithShortNames(fun.getValueParameters().get(0).getType()); + String string = psiType + ""|"" + jetType; + + return ""int|Int"".equals(string) || ""Object|Any?"".equals(string); + } + + return true; + } + return false; + } + + @Nullable + private static PsiMethod findMethod(@NotNull PsiMethod[] methods, @NotNull FunctionDescriptor fun) { + PsiMethod found = null; + for (PsiMethod method : methods) { + if (match(method, fun)) { + if (found != null) { + throw new AssertionError(""Duplicate for "" + fun); + } + + found = method; + } + } + + return found; + } + + private void appendBeforeClass(@NotNull ClassDescriptor kotlinClass, @NotNull PsiClass psiClass) { + String psiFqName = psiClass.getQualifiedName(); + String kotlinFqName = DescriptorUtils.getFQName(kotlinClass).toSafe().getFqName(); + + assert kotlinFqName.startsWith(BUILTINS_FQNAME_PREFIX); + String kotlinSubQualifiedName = kotlinFqName.substring(BUILTINS_FQNAME_PREFIX.length()); + printer.println(""put(b, \"""", psiFqName, ""\"", \"""", kotlinSubQualifiedName, ""\"","").pushIndent(); + } + + private void appendClass(@NotNull List> methods2Functions) { + int index = 0; + for (Pair method2Function : methods2Functions) { + printer.print(""pair(\"""", serializePsiMethod(method2Function.first), ""\"", \"""", serializeFunction(method2Function.second), + ""\"")""); + + if (index != methods2Functions.size() - 1) { + printer.printWithNoIndent("",""); + } + + printer.println(); + + index++; + } + } + + private void appendAfterClass() { + printer.popIndent().println("");"").println(); + } + + + public String toString() { + return buf.toString(); + } + } + + private GenerateJavaToKotlinMethodMap() { + } +} diff --git a/jdk-annotations/java/util/annotations.xml b/jdk-annotations/java/util/annotations.xml index 3251649264e78..c1f62eced16e3 100644 --- a/jdk-annotations/java/util/annotations.xml +++ b/jdk-annotations/java/util/annotations.xml @@ -1,4 +1,10 @@ + + + + + + @@ -679,12 +685,12 @@ - + - + @@ -699,7 +705,7 @@ - + " 614faccf1d353c3b4835e6df0e6902839d54b5f6,hadoop,YARN-1910. Fixed a race condition in TestAMRMTokens- that causes the test to fail more often on Windows. Contributed by Xuan Gong.- svn merge --ignore-ancestry -c 1586192 ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1586193 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 2abb35dfa9b02..188a80035ac85 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -79,6 +79,9 @@ Release 2.4.1 - UNRELEASED YARN-1908. Fixed DistributedShell to not fail in secure clusters. (Vinod Kumar Vavilapalli and Jian He via vinodkv) + YARN-1910. Fixed a race condition in TestAMRMTokens that causes the test to + fail more often on Windows. (Xuan Gong via vinodkv) + Release 2.4.0 - 2014-04-07 INCOMPATIBLE CHANGES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestAMRMTokens.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestAMRMTokens.java index aa894c5f6a920..64602bd888e27 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestAMRMTokens.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestAMRMTokens.java @@ -48,6 +48,7 @@ import org.apache.hadoop.yarn.server.resourcemanager.TestAMAuthorization.MyContainerManager; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; +import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event.RMAppAttemptContainerFinishedEvent; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.Records; @@ -63,6 +64,7 @@ public class TestAMRMTokens { private static final Log LOG = LogFactory.getLog(TestAMRMTokens.class); private final Configuration conf; + private static final int maxWaitAttempts = 50; @Parameters public static Collection configs() { @@ -153,6 +155,16 @@ public void testTokenExpiry() throws Exception { new RMAppAttemptContainerFinishedEvent(applicationAttemptId, containerStatus)); + // Make sure the RMAppAttempt is at Finished State. + // Both AMRMToken and ClientToAMToken have been removed. + int count = 0; + while (attempt.getState() != RMAppAttemptState.FINISHED + && count < maxWaitAttempts) { + Thread.sleep(100); + count++; + } + Assert.assertTrue(attempt.getState() == RMAppAttemptState.FINISHED); + // Now simulate trying to allocate. RPC call itself should throw auth // exception. rpc.stopProxy(rmClient, conf); // To avoid using cached client" 649a65fae047377bf52978ef47f3d50020f1c048,Delta Spike,"DELTASPIKE-277 create a proper unit test and remove unused imports ",p,https://github.com/apache/deltaspike,"diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/message/JsfMessageProducer.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/message/JsfMessageProducer.java index 2a26c82d4..ca5fca5d6 100644 --- a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/message/JsfMessageProducer.java +++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/message/JsfMessageProducer.java @@ -26,7 +26,6 @@ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -import org.apache.deltaspike.core.util.ReflectionUtils; import org.apache.deltaspike.jsf.message.JsfMessage; /** diff --git a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/JsfMessageTest.java b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/JsfMessageTest.java index c01ff4d7d..2e1767ad1 100644 --- a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/JsfMessageTest.java +++ b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/JsfMessageTest.java @@ -34,9 +34,13 @@ import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; +import org.junit.Assert; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; +import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; /** @@ -76,15 +80,27 @@ public void testViewScopedContext() throws Exception //X TODO remove, it's just for debugging the server side: //X Thread.sleep(600000L); -/*X - WebElement inputField = driver.findElement(By.id(""test:valueInput"")); - inputField.sendKeys(""23""); - WebElement button = driver.findElement(By.id(""test:saveButton"")); - button.click(); + // check the JSF FacesMessages + + Assert.assertNotNull(ExpectedConditions.presenceOfElementLocated(By.xpath(""id('messages')"")).apply(driver)); + + Assert.assertTrue(ExpectedConditions.textToBePresentInElement( + By.xpath(""id('messages')/ul/li[1]""), ""message with details warnInfo!"").apply(driver)); + + Assert.assertTrue(ExpectedConditions.textToBePresentInElement( + By.xpath(""id('messages')/ul/li[2]""), ""message without detail but parameter errorInfo."").apply(driver)); + + Assert.assertTrue(ExpectedConditions.textToBePresentInElement( + By.xpath(""id('messages')/ul/li[3]""), ""a simple message without a param."").apply(driver)); + + Assert.assertTrue(ExpectedConditions.textToBePresentInElement( + By.xpath(""id('messages')/ul/li[4]""), ""simple message with a string param fatalInfo."").apply(driver)); + + // check the free message usage + Assert.assertTrue(ExpectedConditions.textToBePresentInElement( + By.id(""test:valueOutput""), ""a simple message without a param."").apply(driver)); - Assert.assertTrue(ExpectedConditions.textToBePresentInElement(By.id(""test:valueOutput""), ""23"").apply(driver)); -*/ } }" 7b22bc146b318790552aa8ec1ece25a3a06d1316,Valadoc,"Add support for cgraphs Based on patch by Richard Schwarting Fixes bug 703688. ",a,https://github.com/GNOME/vala/,"diff --git a/configure.ac b/configure.ac index 79aa766f38..d4d639055b 100644 --- a/configure.ac +++ b/configure.ac @@ -53,6 +53,35 @@ AC_SUBST(LIBGEE_LIBS) +AC_MSG_CHECKING([for CGRAPH]) +valadoc_tmp_LIBADD=""$LIBADD"" +valadoc_tmp_CFLAGS=""$CFLAGGS"" +LIBADD=""$LIBADD $LIBGVC_LIBS"" +CFLAGS=""$CFLAGS $LIBGVC_CFLAGS"" +AC_RUN_IFELSE( + [AC_LANG_SOURCE([ + #include + + int main(void) { + #ifdef WITH_CGRAPH + return 0; + #else + return -1; + #endif + } + ])], [ + AC_MSG_RESULT([yes]) + VALAFLAGS=""$VALAFLAGS -D WITH_CGRAPH"" + have_cgraph=yes + ], [ + AC_MSG_RESULT([no]) + have_cgraph=no + ] +) +LIBADD=""$valadoc_tmp_LIBADD"" +CFLAGS=""$valadoc_tmp_CFLAGS"" +AM_CONDITIONAL(HAVE_CGRAPH, test ""$have_cgraph"" = ""yes"") + ## ## Drivers: diff --git a/src/doclets/devhelp/Makefile.am b/src/doclets/devhelp/Makefile.am index e7c2446290..de82ec1ed2 100644 --- a/src/doclets/devhelp/Makefile.am +++ b/src/doclets/devhelp/Makefile.am @@ -4,6 +4,7 @@ NULL = AM_CFLAGS = -g \ -DPACKAGE_ICONDIR=\""$(datadir)/valadoc/icons/\"" \ -I ../../libvaladoc/ \ + $(LIBGVC_CFLAGS) \ $(GLIB_CFLAGS) \ $(LIBGEE_CFLAGS) \ $(NULL) diff --git a/src/doclets/gtkdoc/Makefile.am b/src/doclets/gtkdoc/Makefile.am index 66dcc5576f..81e3607533 100644 --- a/src/doclets/gtkdoc/Makefile.am +++ b/src/doclets/gtkdoc/Makefile.am @@ -5,6 +5,7 @@ AM_CFLAGS = -g \ -DPACKAGE_ICONDIR=\""$(datadir)/valadoc/icons/\"" \ -I ../../libvaladoc/ \ $(GLIB_CFLAGS) \ + $(LIBGVC_CFLAGS) \ $(LIBGEE_CFLAGS) \ $(NULL) diff --git a/src/doclets/htm/Makefile.am b/src/doclets/htm/Makefile.am index 5f3be836e2..7127e1d350 100644 --- a/src/doclets/htm/Makefile.am +++ b/src/doclets/htm/Makefile.am @@ -4,10 +4,21 @@ NULL = AM_CFLAGS = -g \ -DPACKAGE_ICONDIR=\""$(datadir)/valadoc/icons/\"" \ -I ../../libvaladoc/ \ + $(LIBGVC_CFLAGS) \ $(GLIB_CFLAGS) \ $(LIBGEE_CFLAGS) \ $(NULL) +# Without the LIBGVC_CFLAGS, we get +# make[5]: Entering directory `/home/richard/.local/src/valadoc/src/doclets/devhelp' +# CC doclet.lo +# In file included from /usr/include/graphviz/gvc.h:17:0, +# from ../../libvaladoc/valadoc-1.0.h:15, +# from doclet.c:28: +# /usr/include/graphviz/types.h:49:20: fatal error: cgraph.h: No such file or directory +# #include +# ^ +# compilation terminated. BUILT_SOURCES = libdoclet.vala.stamp diff --git a/src/libvaladoc/charts/chart.vala b/src/libvaladoc/charts/chart.vala index f4b99088c3..03dab30f75 100644 --- a/src/libvaladoc/charts/chart.vala +++ b/src/libvaladoc/charts/chart.vala @@ -27,7 +27,9 @@ public class Valadoc.Charts.Chart : Api.Visitor { protected Factory factory; static construct { + #if !WITH_CGRAPH Gvc.init (); + #endif } public Chart (Factory factory, Api.Node node) { diff --git a/src/libvaladoc/charts/chartfactory.vala b/src/libvaladoc/charts/chartfactory.vala index 6a3351a7c0..c2582ab9f3 100644 --- a/src/libvaladoc/charts/chartfactory.vala +++ b/src/libvaladoc/charts/chartfactory.vala @@ -23,7 +23,11 @@ public abstract class Valadoc.Charts.Factory : Object { protected Gvc.Node create_type (Gvc.Graph graph, Api.Node item) { + #if WITH_CGRAPH + return graph.create_node (item.get_full_name (), 1); + #else return graph.create_node (item.get_full_name ()); + #endif } public abstract Gvc.Graph create_graph (Api.Node item); diff --git a/src/libvaladoc/charts/simplechartfactory.vala b/src/libvaladoc/charts/simplechartfactory.vala index a1f09fbaae..06da97e133 100644 --- a/src/libvaladoc/charts/simplechartfactory.vala +++ b/src/libvaladoc/charts/simplechartfactory.vala @@ -31,7 +31,11 @@ public class Valadoc.Charts.SimpleFactory : Charts.Factory { } public override Gvc.Graph create_graph (Api.Node item) { + #if WITH_CGRAPH + var graph = new Gvc.Graph (item.get_full_name (), Gvc.Agdirected, 0); + #else var graph = new Gvc.Graph (item.get_full_name (), Gvc.GraphKind.AGDIGRAPH); + #endif return graph; }" c9a360e36059aa46d7090e879762d44d54fa2782,hbase,HBASE-7197. Add multi get to RemoteHTable- (Elliott Clark)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1422143 13f79535-47bb-0310-9956-ffa450edef68-,a,https://github.com/apache/hbase,"diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/client/RemoteHTable.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/client/RemoteHTable.java index beebe960b05b..92fe09202f61 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/client/RemoteHTable.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/client/RemoteHTable.java @@ -148,6 +148,29 @@ protected String buildRowSpec(final byte[] row, final Map familyMap, return sb.toString(); } + protected String buildMultiRowSpec(final byte[][] rows, int maxVersions) { + StringBuilder sb = new StringBuilder(); + sb.append('/'); + sb.append(Bytes.toStringBinary(name)); + sb.append(""/multiget/""); + if (rows == null || rows.length == 0) { + return sb.toString(); + } + sb.append(""?""); + for(int i=0; i results = new ArrayList(); for (RowModel row: model.getRows()) { @@ -273,31 +296,66 @@ public Result get(Get get) throws IOException { if (get.getFilter() != null) { LOG.warn(""filters not supported on gets""); } + Result[] results = getResults(spec); + if (results.length > 0) { + if (results.length > 1) { + LOG.warn(""too many results for get ("" + results.length + "")""); + } + return results[0]; + } else { + return new Result(); + } + } + + public Result[] get(List gets) throws IOException { + byte[][] rows = new byte[gets.size()][]; + int maxVersions = 1; + int count = 0; + + for(Get g:gets) { + + if ( count == 0 ) { + maxVersions = g.getMaxVersions(); + } else if (g.getMaxVersions() != maxVersions) { + LOG.warn(""MaxVersions on Gets do not match, using the first in the list (""+maxVersions+"")""); + } + + if (g.getFilter() != null) { + LOG.warn(""filters not supported on gets""); + } + + rows[count] = g.getRow(); + count ++; + } + + String spec = buildMultiRowSpec(rows, maxVersions); + + return getResults(spec); + } + + private Result[] getResults(String spec) throws IOException { for (int i = 0; i < maxRetries; i++) { Response response = client.get(spec, Constants.MIMETYPE_PROTOBUF); int code = response.getCode(); switch (code) { - case 200: - CellSetModel model = new CellSetModel(); - model.getObjectFromMessage(response.getBody()); - Result[] results = buildResultFromModel(model); - if (results.length > 0) { - if (results.length > 1) { - LOG.warn(""too many results for get ("" + results.length + "")""); + case 200: + CellSetModel model = new CellSetModel(); + model.getObjectFromMessage(response.getBody()); + Result[] results = buildResultFromModel(model); + if ( results.length > 0) { + return results; } - return results[0]; - } - // fall through - case 404: - return new Result(); + // fall through + case 404: + return new Result[0]; - case 509: - try { - Thread.sleep(sleepTime); - } catch (InterruptedException e) { } - break; - default: - throw new IOException(""get request returned "" + code); + case 509: + try { + Thread.sleep(sleepTime); + } catch (InterruptedException e) { } + break; + default: + throw new IOException(""get request returned "" + code); } } throw new IOException(""get request timed out""); @@ -708,11 +766,6 @@ public Object[] batchCallback(List actions, Batch.Callback throw new IOException(""batchCallback not supported""); } - @Override - public Result[] get(List gets) throws IOException { - throw new IOException(""get(List) not supported""); - } - @Override public T coprocessorProxy(Class protocol, byte[] row) { diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/rest/client/TestRemoteTable.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/rest/client/TestRemoteTable.java index 01e23d99a0ed..b52a167fbbc9 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/rest/client/TestRemoteTable.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/rest/client/TestRemoteTable.java @@ -216,6 +216,45 @@ public void testGet() throws IOException { assertEquals(2, count); } + @Test + public void testMultiGet() throws Exception { + ArrayList gets = new ArrayList(); + gets.add(new Get(ROW_1)); + gets.add(new Get(ROW_2)); + Result[] results = remoteTable.get(gets); + assertNotNull(results); + assertEquals(2, results.length); + assertEquals(1, results[0].size()); + assertEquals(2, results[1].size()); + + //Test Versions + gets = new ArrayList(); + Get g = new Get(ROW_1); + g.setMaxVersions(3); + gets.add(g); + gets.add(new Get(ROW_2)); + results = remoteTable.get(gets); + assertNotNull(results); + assertEquals(2, results.length); + assertEquals(1, results[0].size()); + assertEquals(3, results[1].size()); + + //404 + gets = new ArrayList(); + gets.add(new Get(Bytes.toBytes(""RESALLYREALLYNOTTHERE""))); + results = remoteTable.get(gets); + assertNotNull(results); + assertEquals(0, results.length); + + gets = new ArrayList(); + gets.add(new Get(Bytes.toBytes(""RESALLYREALLYNOTTHERE""))); + gets.add(new Get(ROW_1)); + gets.add(new Get(ROW_2)); + results = remoteTable.get(gets); + assertNotNull(results); + assertEquals(0, results.length); + } + @Test public void testPut() throws IOException { Put put = new Put(ROW_3);" 5bc30fcc6c587c5b4581fbcc772cb4625edf2d4c,Mylyn Reviews,"Merge branch 'master' of git://git.eclipse.org/gitroot/mylyn/org.eclipse.mylyn.reviews ",p,https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews,"diff --git a/gerrit/org.eclipse.mylyn.gerrit.ui/src/org/eclipse/mylyn/internal/gerrit/ui/wizards/GerritCustomQueryPage.java b/gerrit/org.eclipse.mylyn.gerrit.ui/src/org/eclipse/mylyn/internal/gerrit/ui/wizards/GerritCustomQueryPage.java index 32074577..133e1cd0 100644 --- a/gerrit/org.eclipse.mylyn.gerrit.ui/src/org/eclipse/mylyn/internal/gerrit/ui/wizards/GerritCustomQueryPage.java +++ b/gerrit/org.eclipse.mylyn.gerrit.ui/src/org/eclipse/mylyn/internal/gerrit/ui/wizards/GerritCustomQueryPage.java @@ -10,6 +10,7 @@ *********************************************************************/ package org.eclipse.mylyn.internal.gerrit.ui.wizards; +import org.eclipse.jface.wizard.IWizardContainer; import org.eclipse.mylyn.internal.gerrit.core.GerritQuery; import org.eclipse.mylyn.tasks.core.IRepositoryQuery; import org.eclipse.mylyn.tasks.core.TaskRepository; @@ -122,7 +123,10 @@ public void keyReleased(KeyEvent e) { SelectionListener buttonSelectionListener = new SelectionListener() { public void widgetSelected(SelectionEvent e) { projectText.setEnabled(byProjectButton.getSelection()); - getContainer().updateButtons(); + IWizardContainer c = getContainer(); + if (c.getCurrentPage() != null) { + c.updateButtons(); + } } public void widgetDefaultSelected(SelectionEvent e) {" fcfbdf64406ac44b771a3c1b91b95d9d9a465391,hadoop,YARN-3181. FairScheduler: Fix up outdated findbugs- issues. (kasha)--(cherry picked from commit c2b185def846f5577a130003a533b9c377b58fab)-,p,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 6d27c85bf5be8..87524586bf320 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -243,6 +243,8 @@ Release 2.7.0 - UNRELEASED YARN-2079. Recover NonAggregatingLogHandler state upon nodemanager restart. (Jason Lowe via junping_du) + YARN-3181. FairScheduler: Fix up outdated findbugs issues. (kasha) + YARN-3124. Fixed CS LeafQueue/ParentQueue to use QueueCapacities to track capacities-by-label. (Wangda Tan via jianhe) diff --git a/hadoop-yarn-project/hadoop-yarn/dev-support/findbugs-exclude.xml b/hadoop-yarn-project/hadoop-yarn/dev-support/findbugs-exclude.xml index c45634e1be07b..70f1a71fbcb74 100644 --- a/hadoop-yarn-project/hadoop-yarn/dev-support/findbugs-exclude.xml +++ b/hadoop-yarn-project/hadoop-yarn/dev-support/findbugs-exclude.xml @@ -142,22 +142,12 @@ - - - - - - - - - - @@ -215,18 +205,6 @@ - - - - - - - - - - - - @@ -426,11 +404,6 @@ - - - - - diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AllocationConfiguration.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AllocationConfiguration.java index 0ea731403029e..9cb767d38a5d5 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AllocationConfiguration.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AllocationConfiguration.java @@ -33,6 +33,9 @@ import com.google.common.annotations.VisibleForTesting; +import javax.annotation.concurrent.ThreadSafe; + +@ThreadSafe public class AllocationConfiguration extends ReservationSchedulerConfiguration { private static final AccessControlList EVERYBODY_ACL = new AccessControlList(""*""); private static final AccessControlList NOBODY_ACL = new AccessControlList("" ""); @@ -204,12 +207,16 @@ public float getFairSharePreemptionThreshold(String queueName) { } public ResourceWeights getQueueWeight(String queue) { - ResourceWeights weight = queueWeights.get(queue); - return (weight == null) ? ResourceWeights.NEUTRAL : weight; + synchronized (queueWeights) { + ResourceWeights weight = queueWeights.get(queue); + return (weight == null) ? ResourceWeights.NEUTRAL : weight; + } } public void setQueueWeight(String queue, ResourceWeights weight) { - queueWeights.put(queue, weight); + synchronized (queueWeights) { + queueWeights.put(queue, weight); + } } public int getUserMaxApps(String user) { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AllocationFileLoaderService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AllocationFileLoaderService.java index 76fa588fc767f..c19aa513e1c1d 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AllocationFileLoaderService.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AllocationFileLoaderService.java @@ -201,7 +201,7 @@ public synchronized void setReloadListener(Listener reloadListener) { * @throws ParserConfigurationException if XML parser is misconfigured. * @throws SAXException if config file is malformed. */ - public synchronized void reloadAllocations() throws IOException, + public void reloadAllocations() throws IOException, ParserConfigurationException, SAXException, AllocationConfigurationException { if (allocFile == null) { return; diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSOpDurations.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSOpDurations.java index c2282fdb736ca..c50f281cb6645 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSOpDurations.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSOpDurations.java @@ -31,6 +31,8 @@ import static org.apache.hadoop.metrics2.lib.Interns.info; import org.apache.hadoop.metrics2.lib.MutableRate; +import javax.annotation.concurrent.ThreadSafe; + /** * Class to capture the performance metrics of FairScheduler. * This should be a singleton. @@ -38,6 +40,7 @@ @InterfaceAudience.Private @InterfaceStability.Unstable @Metrics(context=""fairscheduler-op-durations"") +@ThreadSafe public class FSOpDurations implements MetricsSource { @Metric(""Duration for a continuous scheduling run"")" c8dec345b6e2ad04ffcede24779dd75efd25d599,Vala,"Add used DBus attribute and fix UnixMountEntry lower_case_cprefix Fixes bug 741089 ",a,https://github.com/GNOME/vala/,"diff --git a/vala/valausedattr.vala b/vala/valausedattr.vala index 793c5bc23b..4a17562848 100644 --- a/vala/valausedattr.vala +++ b/vala/valausedattr.vala @@ -67,6 +67,8 @@ public class Vala.UsedAttr : CodeVisitor { ""GtkChild"", ""name"", ""internal"", """", ""GtkTemplate"", ""ui"", """", ""GtkCallback"", ""name"", """", + + ""DBus"", ""name"", ""no_reply"", ""result"", ""use_string_marshalling"", ""value"", ""signature"", """", ""GIR"", ""name"", """" diff --git a/vapi/gio-unix-2.0.vapi b/vapi/gio-unix-2.0.vapi index c426491346..c662002dfb 100644 --- a/vapi/gio-unix-2.0.vapi +++ b/vapi/gio-unix-2.0.vapi @@ -73,34 +73,23 @@ namespace GLib { public bool close_fd { get; set; } public int fd { get; construct; } } - [CCode (cheader_filename = ""gio/gunixmounts.h"", cname = ""GUnixMountEntry"", free_function = ""g_unix_mount_free"", lower_case_prefix = ""g_unix_mount_"")] + [CCode (cheader_filename = ""gio/gunixmounts.h"", cname = ""GUnixMountEntry"", free_function = ""g_unix_mount_free"", lower_case_cprefix = ""g_unix_mount_"")] [Compact] public class UnixMountEntry { [CCode (cname = ""g_unix_mount_at"")] public UnixMountEntry (string mount_path, uint64 time_read); - [CCode (cname = ""g_unix_mount_compare"")] public int compare (GLib.UnixMountEntry mount); [CCode (cheader_filename = ""gio/gunixmounts.h"", cname = ""g_unix_mounts_get"")] public static GLib.List @get (out uint64 time_read = null); - [CCode (cname = ""g_unix_mount_get_device_path"")] public unowned string get_device_path (); - [CCode (cname = ""g_unix_mount_get_fs_type"")] public unowned string get_fs_type (); - [CCode (cname = ""g_unix_mount_get_mount_path"")] public unowned string get_mount_path (); - [CCode (cname = ""g_unix_mount_guess_can_eject"")] public bool guess_can_eject (); - [CCode (cname = ""g_unix_mount_guess_icon"")] public GLib.Icon guess_icon (); - [CCode (cname = ""g_unix_mount_guess_name"")] public string guess_name (); - [CCode (cname = ""g_unix_mount_guess_should_display"")] public bool guess_should_display (); - [CCode (cname = ""g_unix_mount_guess_symbolic_icon"")] public GLib.Icon guess_symbolic_icon (); - [CCode (cname = ""g_unix_mount_is_readonly"")] public bool is_readonly (); - [CCode (cname = ""g_unix_mount_is_system_internal"")] public bool is_system_internal (); } [CCode (cheader_filename = ""gio/gunixmounts.h"")] diff --git a/vapi/packages/gio-unix-2.0/gio-unix-2.0-custom.vala b/vapi/packages/gio-unix-2.0/gio-unix-2.0-custom.vala index 4b2b8741f6..424e2ec29c 100644 --- a/vapi/packages/gio-unix-2.0/gio-unix-2.0-custom.vala +++ b/vapi/packages/gio-unix-2.0/gio-unix-2.0-custom.vala @@ -22,31 +22,20 @@ namespace GLib { [Compact] - [CCode (cname = ""GUnixMountEntry"", cheader_filename = ""gio/gunixmounts.h"", lower_case_prefix = ""g_unix_mount_"", free_function = ""g_unix_mount_free"")] + [CCode (cname = ""GUnixMountEntry"", cheader_filename = ""gio/gunixmounts.h"", lower_case_cprefix = ""g_unix_mount_"", free_function = ""g_unix_mount_free"")] public class UnixMountEntry { [CCode (cname = ""g_unix_mount_at"")] public UnixMountEntry (string mount_path, uint64 time_read); - [CCode (cname = ""g_unix_mount_compare"")] public int compare (GLib.UnixMountEntry mount); - [CCode (cname = ""g_unix_mount_get_device_path"")] public unowned string get_device_path (); - [CCode (cname = ""g_unix_mount_get_fs_type"")] public unowned string get_fs_type (); - [CCode (cname = ""g_unix_mount_get_mount_path"")] public unowned string get_mount_path (); - [CCode (cname = ""g_unix_mount_guess_can_eject"")] public bool guess_can_eject (); - [CCode (cname = ""g_unix_mount_guess_icon"")] public GLib.Icon guess_icon (); - [CCode (cname = ""g_unix_mount_guess_name"")] public string guess_name (); - [CCode (cname = ""g_unix_mount_guess_should_display"")] public bool guess_should_display (); - [CCode (cname = ""g_unix_mount_guess_symbolic_icon"")] public GLib.Icon guess_symbolic_icon (); - [CCode (cname = ""g_unix_mount_is_readonly"")] public bool is_readonly (); - [CCode (cname = ""g_unix_mount_is_system_internal"")] public bool is_system_internal (); [CCode (cname = ""g_unix_mounts_get"", cheader_filename = ""gio/gunixmounts.h"")]" 9c301fc289a15a84552950737df03f9d0487150f,Delta Spike,"DELTASPIKE-382 add ConfigFilter mechanism This allows to filter DeltaSpike configuration values, e.g. for applying decryption of secure configuration values on the fly. ",a,https://github.com/apache/deltaspike,"diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java index b7802a38b..4cd956e33 100644 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java @@ -32,6 +32,7 @@ import javax.enterprise.inject.Typed; import org.apache.deltaspike.core.api.projectstage.ProjectStage; +import org.apache.deltaspike.core.spi.config.ConfigFilter; import org.apache.deltaspike.core.spi.config.ConfigSource; import org.apache.deltaspike.core.spi.config.ConfigSourceProvider; import org.apache.deltaspike.core.util.ClassUtils; @@ -58,6 +59,13 @@ public final class ConfigResolver private static Map configSources = new ConcurrentHashMap(); + /** + * The content of this map will hold the List of ConfigFilters + * for each WebApp/EAR, etc (thus the ClassLoader). + */ + private static Map> configFilters + = new ConcurrentHashMap>(); + private static volatile ProjectStage projectStage = null; private ConfigResolver() @@ -96,6 +104,35 @@ public static synchronized void freeConfigSources() configSources.remove(ClassUtils.getClassLoader(null)); } + /** + * Add a {@link ConfigFilter} to the ConfigResolver. + * This will only affect the current WebApp + * (or more precisely the current ClassLoader and it's children). + * @param configFilter + */ + public static void addConfigFilter(ConfigFilter configFilter) + { + + List currentConfigFilters = getConfigFilters(); + currentConfigFilters.add(configFilter); + } + + /** + * @return the {@link ConfigFilter}s for the current application. + */ + public static List getConfigFilters() + { + ClassLoader cl = ClassUtils.getClassLoader(null); + List currentConfigFilters = configFilters.get(cl); + if (currentConfigFilters == null) + { + currentConfigFilters = new ArrayList(); + configFilters.put(cl, currentConfigFilters); + } + + return currentConfigFilters; + } + /** * Resolve the property value by going through the list of configured {@link ConfigSource}s * and use the one with the highest priority. If no configured value has been found that @@ -133,8 +170,8 @@ public static String getPropertyValue(String key) if (value != null) { LOG.log(Level.FINE, ""found value {0} for key {1} in ConfigSource {2}."", - new Object[]{value, key, configSource.getConfigName()}); - return value; + new Object[]{filterConfigValueForLog(key, value), key, configSource.getConfigName()}); + return filterConfigValue(key, value); } LOG.log(Level.FINER, ""NO value found for key {0} in ConfigSource {1}."", @@ -275,9 +312,13 @@ public static List getAllPropertyValues(String key) { value = configSource.getPropertyValue(key); - if (value != null && !result.contains(value)) + if (value != null) { - result.add(value); + value = filterConfigValue(key, value); + if (!result.contains(value)) + { + result.add(value); + } } } @@ -399,5 +440,31 @@ private static String fallbackToDefaultIfEmpty(String key, String value, String return value; } + private static String filterConfigValue(String key, String value) + { + List currentConfigFilters = getConfigFilters(); + + String filteredValue = value; + + for (ConfigFilter filter : currentConfigFilters) + { + filteredValue = filter.filterValue(key, filteredValue); + } + return filteredValue; + } + + private static String filterConfigValueForLog(String key, String value) + { + List currentConfigFilters = getConfigFilters(); + + String logValue = value; + + for (ConfigFilter filter : currentConfigFilters) + { + logValue = filter.filterValueForLog(key, logValue); + } + return logValue; + } + } diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/config/ConfigFilter.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/config/ConfigFilter.java new file mode 100644 index 000000000..5f851e2c6 --- /dev/null +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/config/ConfigFilter.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.deltaspike.core.spi.config; + +/** + * A filter which can be added to the + * {@link org.apache.deltaspike.core.api.config.ConfigResolver}. + * The filter can be used to decrypt config values or prepare + * values for logging. + */ +public interface ConfigFilter +{ + /** + * Filter the given configuration value + * @param key + * @param value + * @return the filtered value or the original input String if no filter shall be applied + */ + String filterValue(String key, String value); + + /** + * Filter the given configuration value for usage in logs. + * This might be used to mask out passwords, etc. + * @param key + * @param value + * @return the filtered value or the original input String if no filter shall be applied + */ + String filterValueForLog(String key, String value); +} diff --git a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java index d30e7de52..6aa81dae6 100644 --- a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java +++ b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java @@ -20,6 +20,7 @@ import org.apache.deltaspike.core.api.config.ConfigResolver; import org.apache.deltaspike.core.api.projectstage.ProjectStage; +import org.apache.deltaspike.core.spi.config.ConfigFilter; import org.apache.deltaspike.core.util.ProjectStageProducer; import org.junit.Assert; import org.junit.Test; @@ -74,7 +75,8 @@ public void testGetProjectStageAwarePropertyValue() } @Test - public void testGetPropertyAwarePropertyValue() { + public void testGetPropertyAwarePropertyValue() + { ProjectStageProducer.setProjectStage(ProjectStage.UnitTest); Assert.assertNull(ConfigResolver.getPropertyAwarePropertyValue(""notexisting"", null)); @@ -100,4 +102,51 @@ public void testGetPropertyAwarePropertyValue() { Assert.assertEquals(""DefaultDataSource"", ConfigResolver.getPropertyAwarePropertyValue(""dataSource"", ""dbvendorX"", null)); Assert.assertEquals(DEFAULT_VALUE, ConfigResolver.getPropertyAwarePropertyValue(""dataSourceX"", ""dbvendorX"", DEFAULT_VALUE)); } + + @Test + public void testConfigFilter() + { + + ConfigFilter configFilter = new TestConfigFilter(); + + Assert.assertEquals(""shouldGetDecrypted: value"", configFilter.filterValue(""somekey.encrypted"", ""value"")); + Assert.assertEquals(""**********"", configFilter.filterValueForLog(""somekey.password"", ""value"")); + + ConfigResolver.addConfigFilter(configFilter); + + Assert.assertEquals(""shouldGetDecrypted: value"", ConfigResolver.getPropertyValue(""testkey4.encrypted"")); + Assert.assertEquals(""shouldGetDecrypted: value"", ConfigResolver.getProjectStageAwarePropertyValue(""testkey4.encrypted"")); + Assert.assertEquals(""shouldGetDecrypted: value"", ConfigResolver.getProjectStageAwarePropertyValue(""testkey4.encrypted"", null)); + Assert.assertEquals(""shouldGetDecrypted: value"", ConfigResolver.getPropertyAwarePropertyValue(""testkey4.encrypted"", ""dbvendor"")); + Assert.assertEquals(""shouldGetDecrypted: value"", ConfigResolver.getPropertyAwarePropertyValue(""testkey4.encrypted"", ""dbvendor"", null)); + + List allPropertyValues = ConfigResolver.getAllPropertyValues(""testkey4.encrypted""); + Assert.assertNotNull(allPropertyValues); + Assert.assertEquals(1, allPropertyValues.size()); + Assert.assertEquals(""shouldGetDecrypted: value"", allPropertyValues.get(0)); + + } + + public static class TestConfigFilter implements ConfigFilter + { + @Override + public String filterValue(String key, String value) + { + if (key.contains(""encrypted"")) + { + return ""shouldGetDecrypted: "" + value; + } + return value; + } + + @Override + public String filterValueForLog(String key, String value) + { + if (key.contains(""password"")) + { + return ""**********""; + } + return value; + } + } } diff --git a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java index d0f2c938b..3b073a9b2 100644 --- a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java +++ b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java @@ -62,6 +62,9 @@ public TestConfigSource() props.put(""dbvendor2.Production"", ""mysql""); props.put(""dbvendor2"", ""postgresql""); + props.put(""testkey4.encrypted"", ""value""); + props.put(""testkey4.password"", ""mysecretvalue""); + } @Override" e98541030c5e0aadfdb194dbb55254f404219600,orientdb,Huge refactoring on GraphDB: - changed class- names in vertex and edge - Optimized memory consumption by removing nested- records - Optimized speed in ORecord.equals() and hashCode(): now avoid field- checks (experimental)--,p,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java index cd054ea61c5..cc4674f4842 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java @@ -185,6 +185,8 @@ public ORecordAbstract save() { OSerializationThreadLocal.INSTANCE.get().clear(); _database.save(this); + + OSerializationThreadLocal.INSTANCE.get().clear(); return this; } diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/ORecordVirtualAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/record/ORecordVirtualAbstract.java index 91a40883f02..6ea13c242fc 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/record/ORecordVirtualAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/record/ORecordVirtualAbstract.java @@ -15,10 +15,8 @@ */ package com.orientechnologies.orient.core.record; -import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; -import java.util.Map.Entry; import com.orientechnologies.orient.core.db.record.ODatabaseRecord; import com.orientechnologies.orient.core.metadata.schema.OType; @@ -73,22 +71,22 @@ public ORecordSchemaAwareAbstract reset() { @Override public int hashCode() { int result = super.hashCode(); - - if (!_recordId.isValid() && _fieldValues != null) - for (Entry field : _fieldValues.entrySet()) { - if (field.getKey() != null) - result += field.getKey().hashCode(); - - if (field.getValue() != null) - if (field.getValue() instanceof ORecord) - // AVOID TO GET THE HASH-CODE OF THE VALUE TO AVOID STACK OVERFLOW FOR CIRCULAR REFS - result += 31 * ((ORecord) field.getValue()).getIdentity().hashCode(); - else if (field.getValue() instanceof Collection) - // AVOID TO GET THE HASH-CODE OF THE VALUE TO AVOID STACK OVERFLOW FOR CIRCULAR REFS - result += ((Collection) field.getValue()).size() * 31; - else - result += field.getValue().hashCode(); - } + // + // if (!_recordId.isValid() && _fieldValues != null) + // for (Entry field : _fieldValues.entrySet()) { + // if (field.getKey() != null) + // result += field.getKey().hashCode(); + // + // if (field.getValue() != null) + // if (field.getValue() instanceof ORecord) + // // AVOID TO GET THE HASH-CODE OF THE VALUE TO AVOID STACK OVERFLOW FOR CIRCULAR REFS + // result += 31 * ((ORecord) field.getValue()).getIdentity().hashCode(); + // else if (field.getValue() instanceof Collection) + // // AVOID TO GET THE HASH-CODE OF THE VALUE TO AVOID STACK OVERFLOW FOR CIRCULAR REFS + // result += ((Collection) field.getValue()).size() * 31; + // else + // result += field.getValue().hashCode(); + // } return result; } @@ -99,37 +97,39 @@ public boolean equals(Object obj) { return false; if (!_recordId.isValid()) { - final ORecordVirtualAbstract other = (ORecordVirtualAbstract) obj; - - // NO PERSISTENT OBJECT: COMPARE EACH FIELDS - if (_fieldValues == null || other._fieldValues == null) - // CAN'T COMPARE FIELDS: RETURN FALSE - return false; - - if (_fieldValues.size() != other._fieldValues.size()) - // FIELD SIZES ARE DIFFERENTS - return false; - - String k; - Object v; - Object otherV; - for (Entry field : _fieldValues.entrySet()) { - k = field.getKey(); - if (k != null && !other.containsField(k)) - // FIELD NOT PRESENT IN THE OTHER RECORD - return false; - - v = _fieldValues.get(k); - otherV = other._fieldValues.get(k); - if (v == null && otherV == null) - continue; - - if (v == null && otherV != null || otherV == null && v != null) - return false; - - if (!v.equals(otherV)) - return false; - } + // + // final ORecordVirtualAbstract other = (ORecordVirtualAbstract) obj; + // + // // NO PERSISTENT OBJECT: COMPARE EACH FIELDS + // if (_fieldValues == null || other._fieldValues == null) + // // CAN'T COMPARE FIELDS: RETURN FALSE + // return false; + // + // if (_fieldValues.size() != other._fieldValues.size()) + // // FIELD SIZES ARE DIFFERENTS + // return false; + // + // String k; + // Object v; + // Object otherV; + // for (Entry field : _fieldValues.entrySet()) { + // k = field.getKey(); + // if (k != null && !other.containsField(k)) + // // FIELD NOT PRESENT IN THE OTHER RECORD + // return false; + // + // v = _fieldValues.get(k); + // otherV = other._fieldValues.get(k); + // if (v == null && otherV == null) + // continue; + // + // if (v == null && otherV != null || otherV == null && v != null) + // return false; + // + // if (!v.equals(otherV)) + // return false; + // } + return false; } return true; diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/OSerializationThreadLocal.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/OSerializationThreadLocal.java index 4faafab4991..b37dfb62aaa 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/OSerializationThreadLocal.java +++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/OSerializationThreadLocal.java @@ -15,7 +15,7 @@ */ package com.orientechnologies.orient.core.serialization.serializer.record; -import java.util.HashMap; +import java.util.IdentityHashMap; import java.util.Map; import com.orientechnologies.orient.core.id.ORecordId; @@ -26,6 +26,6 @@ public class OSerializationThreadLocal extends ThreadLocal, ORecordId> initialValue() { - return new HashMap, ORecordId>(); + return new IdentityHashMap, ORecordId>(); } } \ No newline at end of file diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerSchemaAware2CSV.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerSchemaAware2CSV.java index 3c99ffa202c..d172294974b 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerSchemaAware2CSV.java +++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerSchemaAware2CSV.java @@ -202,6 +202,8 @@ protected String toString(ORecordInternal iRecord, final String iFormat, fina i++; } + + iMarshalledRecords.remove(record); return buffer.toString(); }" b753b88a432fca3a8947a1ea0743e44f626e23a2,Valadoc,"Add warning & note tags ",a,https://github.com/GNOME/vala/,"diff --git a/icons/Makefile.am b/icons/Makefile.am index 5869bff058..4859e248bd 100644 --- a/icons/Makefile.am +++ b/icons/Makefile.am @@ -5,6 +5,7 @@ iconsdir = $(datadir)/valadoc/icons dist_icons_DATA = \ + tip.png \ warning.png \ abstractclass.png \ abstractmethod.png \ diff --git a/icons/tip.png b/icons/tip.png new file mode 100644 index 0000000000..6ccf512f3d Binary files /dev/null and b/icons/tip.png differ diff --git a/src/doclets/gtkdoc/commentconverter.vala b/src/doclets/gtkdoc/commentconverter.vala index a0c3372ce3..e10b8aa3a5 100755 --- a/src/doclets/gtkdoc/commentconverter.vala +++ b/src/doclets/gtkdoc/commentconverter.vala @@ -172,7 +172,19 @@ public class Gtkdoc.CommentConverter : ContentVisitor { current_builder.append (""""); } } - + + public override void visit_warning (Warning element) { + current_builder.append (""""); + element.accept_children (this); + current_builder.append (""""); + } + + public override void visit_note (Note element) { + current_builder.append (""""); + element.accept_children (this); + current_builder.append (""""); + } + public override void visit_page (Page page) { page.accept_children (this); } diff --git a/src/libvaladoc/Makefile.am b/src/libvaladoc/Makefile.am index 310a3dbd13..fe3115c8e1 100755 --- a/src/libvaladoc/Makefile.am +++ b/src/libvaladoc/Makefile.am @@ -26,11 +26,13 @@ libvaladoc_la_VALASOURCES = \ moduleloader.vala \ settings.vala \ markupwriter.vala \ + gtkdocmarkupwriter.vala \ devhelp-markupwriter.vala \ ctyperesolver.vala \ markupsourcelocation.vala \ markuptokentype.vala \ markupreader.vala \ + gtkdocrenderer.vala \ documentation/commentscanner.vala \ documentation/documentation.vala \ documentation/documentationparser.vala \ @@ -103,6 +105,8 @@ libvaladoc_la_VALASOURCES = \ content/listitem.vala \ content/page.vala \ content/paragraph.vala \ + content/warning.vala \ + content/note.vala \ content/resourcelocator.vala \ content/run.vala \ content/sourcecode.vala \ diff --git a/src/libvaladoc/content/contentfactory.vala b/src/libvaladoc/content/contentfactory.vala index 55c44f7ac0..19cf41be21 100755 --- a/src/libvaladoc/content/contentfactory.vala +++ b/src/libvaladoc/content/contentfactory.vala @@ -76,6 +76,13 @@ public class Valadoc.Content.ContentFactory : Object { return (Paragraph) configure (new Paragraph ()); } + public Warning create_warning () { + return (Warning) configure (new Warning ()); + } + public Note create_note () { + return (Note) configure (new Note ()); + } + public Run create_run (Run.Style style) { return (Run) configure (new Run (style)); } diff --git a/src/libvaladoc/content/contentvisitor.vala b/src/libvaladoc/content/contentvisitor.vala index bacffc3ddf..3eb3a4b3d4 100755 --- a/src/libvaladoc/content/contentvisitor.vala +++ b/src/libvaladoc/content/contentvisitor.vala @@ -52,6 +52,12 @@ public abstract class Valadoc.Content.ContentVisitor : Object { public virtual void visit_paragraph (Paragraph element) { } + public virtual void visit_warning (Warning element) { + } + + public virtual void visit_note (Note element) { + } + public virtual void visit_page (Page element) { } diff --git a/src/libvaladoc/content/note.vala b/src/libvaladoc/content/note.vala new file mode 100755 index 0000000000..d2b16c557c --- /dev/null +++ b/src/libvaladoc/content/note.vala @@ -0,0 +1,40 @@ +/* note.vala + * + * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Author: + * Didier 'Ptitjes Villevalois + */ + +using Gee; + + +public class Valadoc.Content.Note : BlockContent, Block { + internal Note () { + base (); + } + + public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + // Check inline content + base.check (api_root, container, reporter, settings); + } + + public override void accept (ContentVisitor visitor) { + visitor.visit_note (this); + } +} + diff --git a/src/libvaladoc/content/warning.vala b/src/libvaladoc/content/warning.vala new file mode 100755 index 0000000000..e848c43f30 --- /dev/null +++ b/src/libvaladoc/content/warning.vala @@ -0,0 +1,40 @@ +/* warning.vala + * + * Copyright (C) 2008-2009 Florian Brosch, Didier Villevalois + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Author: + * Didier 'Ptitjes Villevalois + */ + +using Gee; + + +public class Valadoc.Content.Warning : BlockContent, Block { + internal Warning () { + base (); + } + + public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { + // Check inline content + base.check (api_root, container, reporter, settings); + } + + public override void accept (ContentVisitor visitor) { + visitor.visit_warning (this); + } +} + diff --git a/src/libvaladoc/documentation/documentationparser.vala b/src/libvaladoc/documentation/documentationparser.vala index b2a96f0252..1b29698dd4 100755 --- a/src/libvaladoc/documentation/documentationparser.vala +++ b/src/libvaladoc/documentation/documentationparser.vala @@ -499,6 +499,50 @@ public class Valadoc.DocumentationParser : Object, ResourceLocator { } }); + Rule warning = + Rule.seq ({ + TokenType.str (""Warning:""), + optional_invisible_spaces, + Rule.many ({ + Rule.seq({optional_invisible_spaces, run}), + TokenType.EOL.action (() => { add_content_space (); }) + }) + }) + .set_name (""Warning"") + .set_start (() => { push (_factory.create_paragraph ()); }) + .set_reduce (() => { + var head = _factory.create_warning (); + head.content.add ((Paragraph) pop ()); + ((BlockContent) peek ()).content.add (head); + + Text last_element = head.content.last () as Text; + if (last_element != null) { + last_element.content._chomp (); + } + }); + + Rule note = + Rule.seq ({ + TokenType.str (""Note:""), + optional_invisible_spaces, + Rule.many ({ + Rule.seq({optional_invisible_spaces, run}), + TokenType.EOL.action (() => { add_content_space (); }) + }) + }) + .set_name (""Note"") + .set_start (() => { push (_factory.create_paragraph ()); }) + .set_reduce (() => { + var head = _factory.create_note (); + head.content.add ((Paragraph) pop ()); + ((BlockContent) peek ()).content.add (head); + + Text last_element = head.content.last () as Text; + if (last_element != null) { + last_element.content._chomp (); + } + }); + Rule indented_item = Rule.seq ({ Rule.many ({ @@ -667,6 +711,8 @@ public class Valadoc.DocumentationParser : Object, ResourceLocator { indented_blocks, table, headline, + warning, + note, paragraph }) .set_name (""Blocks""); diff --git a/src/libvaladoc/html/htmlmarkupwriter.vala b/src/libvaladoc/html/htmlmarkupwriter.vala index 7599d18510..13e6cd0ebd 100755 --- a/src/libvaladoc/html/htmlmarkupwriter.vala +++ b/src/libvaladoc/html/htmlmarkupwriter.vala @@ -24,8 +24,14 @@ using GLib; using Valadoc.Content; public class Valadoc.Html.MarkupWriter : Valadoc.MarkupWriter { + private unowned FileStream stream; + public MarkupWriter (FileStream stream, bool xml_declaration = true) { - base (stream, xml_declaration); + // avoid broken implicit copy + unowned FileStream _stream = stream; + + base ((str) => { _stream.printf (str); }, xml_declaration); + this.stream = stream; } public MarkupWriter add_usemap (Charts.Chart chart) { diff --git a/src/libvaladoc/html/htmlrenderer.vala b/src/libvaladoc/html/htmlrenderer.vala index 7c79047d52..c6148ae6db 100755 --- a/src/libvaladoc/html/htmlrenderer.vala +++ b/src/libvaladoc/html/htmlrenderer.vala @@ -341,6 +341,23 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer { writer.end_tag (""p""); } + private void visit_notification_block (BlockContent element, string headline) { + writer.start_tag (""div"", {""class"", ""main_notification_block""}); + writer.start_tag (""span"", {""class"", ""main_block_headline""}).text (headline).end_tag (""span"").text ("" ""); + writer.start_tag (""span"", {""class"", ""main_block_content""}); + element.accept_children (this); + writer.end_tag (""span""); + writer.end_tag (""div""); + } + + public override void visit_warning (Warning element) { + visit_notification_block (element, ""Warning:""); + } + + public override void visit_note (Note element) { + visit_notification_block (element, ""Note:""); + } + public override void visit_run (Run element) { string tag = null; string css_type = null;" 296212eab186b860fd9494db9ed238b341fc2975,kotlin,Merge two JetTypeMapper-mapToCallableMethod- methods--,p,https://github.com/JetBrains/kotlin,"diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/ExpressionCodegen.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/ExpressionCodegen.java index 2be9032ebddaa..896f430d59004 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/ExpressionCodegen.java +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/ExpressionCodegen.java @@ -1472,7 +1472,7 @@ public Unit invoke(InstructionAdapter v) { ConstructorDescriptor constructorToCall = SamCodegenUtil.resolveSamAdapter(superConstructor); List superValueParameters = superConstructor.getValueParameters(); int params = superValueParameters.size(); - List superMappedTypes = typeMapper.mapToCallableMethod(constructorToCall).getValueParameterTypes(); + List superMappedTypes = typeMapper.mapToCallableMethod(constructorToCall, false).getValueParameterTypes(); assert superMappedTypes.size() >= params : String .format(""Incorrect number of mapped parameters vs arguments: %d < %d for %s"", superMappedTypes.size(), params, classDescriptor); @@ -3414,7 +3414,7 @@ public Unit invoke(InstructionAdapter v) { pushClosureOnStack(constructor.getContainingDeclaration(), dispatchReceiver == null, defaultCallGenerator); constructor = SamCodegenUtil.resolveSamAdapter(constructor); - CallableMethod method = typeMapper.mapToCallableMethod(constructor); + CallableMethod method = typeMapper.mapToCallableMethod(constructor, false); invokeMethodWithArguments(method, resolvedCall, StackValue.none()); return Unit.INSTANCE$; diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/FunctionCodegen.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/FunctionCodegen.java index 43c94286739ef..b1c257a942940 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/FunctionCodegen.java +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/FunctionCodegen.java @@ -664,13 +664,7 @@ public static void generateDefaultImplBody( generator.putValueIfNeeded(parameterDescriptor, type, StackValue.local(parameterIndex, type)); } - CallableMethod method; - if (functionDescriptor instanceof ConstructorDescriptor) { - method = state.getTypeMapper().mapToCallableMethod((ConstructorDescriptor) functionDescriptor); - } - else { - method = state.getTypeMapper().mapToCallableMethod(functionDescriptor, false); - } + CallableMethod method = state.getTypeMapper().mapToCallableMethod(functionDescriptor, false); generator.genCallWithoutAssertions(method, codegen); diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java index dbd04bd4121ca..da405f940ff91 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java @@ -937,17 +937,16 @@ private void generateMethodCallTo( @Nullable FunctionDescriptor accessorDescriptor, @NotNull InstructionAdapter iv ) { - boolean isConstructor = functionDescriptor instanceof ConstructorDescriptor; - boolean accessorIsConstructor = accessorDescriptor instanceof AccessorForConstructorDescriptor; - - boolean superCall = accessorDescriptor instanceof AccessorForCallableDescriptor && - ((AccessorForCallableDescriptor) accessorDescriptor).getSuperCallExpression() != null; - CallableMethod callableMethod = isConstructor ? - typeMapper.mapToCallableMethod((ConstructorDescriptor) functionDescriptor) : - typeMapper.mapToCallableMethod(functionDescriptor, superCall); + CallableMethod callableMethod = typeMapper.mapToCallableMethod( + functionDescriptor, + accessorDescriptor instanceof AccessorForCallableDescriptor && + ((AccessorForCallableDescriptor) accessorDescriptor).getSuperCallExpression() != null + ); int reg = 1; - if (isConstructor && !accessorIsConstructor) { + + boolean accessorIsConstructor = accessorDescriptor instanceof AccessorForConstructorDescriptor; + if (!accessorIsConstructor && functionDescriptor instanceof ConstructorDescriptor) { iv.anew(callableMethod.getOwner()); iv.dup(); reg = 0; @@ -1496,8 +1495,8 @@ private void generateDelegatorToConstructorCall( iv.load(0, OBJECT_TYPE); ConstructorDescriptor delegateConstructor = SamCodegenUtil.resolveSamAdapter(codegen.getConstructorDescriptor(delegationConstructorCall)); - CallableMethod delegateConstructorCallable = typeMapper.mapToCallableMethod(delegateConstructor); - CallableMethod callable = typeMapper.mapToCallableMethod(constructorDescriptor); + CallableMethod delegateConstructorCallable = typeMapper.mapToCallableMethod(delegateConstructor, false); + CallableMethod callable = typeMapper.mapToCallableMethod(constructorDescriptor, false); List delegatingParameters = delegateConstructorCallable.getValueParameters(); List parameters = callable.getValueParameters(); @@ -1711,7 +1710,7 @@ private void initializeEnumConstant(@NotNull List enumEntries, int if (delegationSpecifiers.size() == 1 && !enumEntryNeedSubclass(bindingContext, enumEntry)) { ResolvedCall resolvedCall = CallUtilPackage.getResolvedCallWithAssert(delegationSpecifiers.get(0), bindingContext); - CallableMethod method = typeMapper.mapToCallableMethod((ConstructorDescriptor) resolvedCall.getResultingDescriptor()); + CallableMethod method = typeMapper.mapToCallableMethod((ConstructorDescriptor) resolvedCall.getResultingDescriptor(), false); codegen.invokeMethodWithArguments(method, resolvedCall, StackValue.none()); } diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/state/JetTypeMapper.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/state/JetTypeMapper.java index dc57b4ac65db6..bf1c4772a95d8 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/state/JetTypeMapper.java +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/state/JetTypeMapper.java @@ -593,6 +593,12 @@ private Type mapKnownAsmType( @NotNull public CallableMethod mapToCallableMethod(@NotNull FunctionDescriptor descriptor, boolean superCall) { + if (descriptor instanceof ConstructorDescriptor) { + JvmMethodSignature method = mapSignature(descriptor); + Type owner = mapClass(((ConstructorDescriptor) descriptor).getContainingDeclaration()); + return new CallableMethod(owner, owner, owner, method, INVOKESPECIAL, null, null, null); + } + DeclarationDescriptor functionParent = descriptor.getOriginal().getContainingDeclaration(); FunctionDescriptor functionDescriptor = unwrapFakeOverride(descriptor.getOriginal()); @@ -1113,17 +1119,6 @@ public JvmMethodSignature mapScriptSignature(@NotNull ScriptDescriptor script, @ return sw.makeJvmMethodSignature(""""); } - @NotNull - public CallableMethod mapToCallableMethod(@NotNull ConstructorDescriptor descriptor) { - JvmMethodSignature method = mapSignature(descriptor); - ClassDescriptor container = descriptor.getContainingDeclaration(); - Type owner = mapClass(container); - if (owner.getSort() != Type.OBJECT) { - throw new IllegalStateException(""type must have been mapped to object: "" + container.getDefaultType() + "", actual: "" + owner); - } - return new CallableMethod(owner, owner, owner, method, INVOKESPECIAL, null, null, null); - } - public Type getSharedVarType(DeclarationDescriptor descriptor) { if (descriptor instanceof SimpleFunctionDescriptor && descriptor.getContainingDeclaration() instanceof FunctionDescriptor) { return asmTypeForAnonymousClass(bindingContext, (FunctionDescriptor) descriptor);" 77f1f5cd336bbd3c7b9d548a4916084bc1e56dc3,orientdb,Console: fixed jdk6 problem in more elegant way- (thanks to Andrey's suggestion)--,p,https://github.com/orientechnologies/orientdb,"diff --git a/commons/src/main/java/com/orientechnologies/common/console/ODFACommandStream.java b/commons/src/main/java/com/orientechnologies/common/console/ODFACommandStream.java index aaeb27f7b7d..804182cb751 100755 --- a/commons/src/main/java/com/orientechnologies/common/console/ODFACommandStream.java +++ b/commons/src/main/java/com/orientechnologies/common/console/ODFACommandStream.java @@ -107,11 +107,10 @@ public String nextCommand() { result = partialResult.toString(); } } else { - try { - result = buffer.subSequence(start, end + 1).toString(); - } catch (NoSuchMethodError e) { - result = buffer.toString().substring(start, end + 1); - } + // DON'T PUT THIS ON ONE LINE ONLY BECAUSE WITH JDK6 subSequence() RETURNS A CHAR CharSequence while JDK7+ RETURNS + // CharBuffer + final CharSequence cs = buffer.subSequence(start, end + 1); + result = cs.toString(); } buffer.position(buffer.position() + position);" 51b603c850765b2734549a1962581ebe5f5f2125,restlet-framework-java,JAX-RS extension continued: - Added an- ObjectFactory to the JAX-RS extension for customized root resource class and- provider instantiation. Contributed by Bruno Dumon.--,a,https://github.com/restlet/restlet-framework-java,"diff --git a/build/tmpl/text/changes.txt b/build/tmpl/text/changes.txt index 050ac19537..ee28f2d5a0 100644 --- a/build/tmpl/text/changes.txt +++ b/build/tmpl/text/changes.txt @@ -66,6 +66,8 @@ Changes log parsing and formatting into three new classes: MessageRepresentation, MessagesRepresentation and RepresentationMessage. Suggested by Matthieu Hug. + - Added an ObjectFactory to the JAX-RS extension for customized root + resource class and provider instantiation. Contributed by Bruno Dumon. - Misc - Updated Grizzly to 1.7.3. - Improved logging consistency. diff --git a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/JaxRsApplication.java b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/JaxRsApplication.java index d3c2a84bc5..0a304ee739 100644 --- a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/JaxRsApplication.java +++ b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/JaxRsApplication.java @@ -73,7 +73,10 @@ */ public class JaxRsApplication extends Application { - /** the {@link Guard} to use. May be null. */ + /** Indicates if any {@link ApplicationConfig} is attached yet */ + private volatile boolean appConfigAttached = false; + + /** The {@link Guard} to use. May be null. */ private volatile Guard guard; /** The {@link JaxRsRouter} to use. */ @@ -82,9 +85,6 @@ public class JaxRsApplication extends Application { /** Indicates, if an {@link HtmlPreferer} should be used or not. */ private volatile boolean preferHtml = true; - /** indicates if any {@link ApplicationConfig} is attached yet */ - private volatile boolean appConfigAttached = false; - /** * Creates an new JaxRsApplication. You should typically use one of the * other constructors, see {@link Restlet#Restlet()}. @@ -248,6 +248,17 @@ public Guard getGuard() { return this.guard; } + /** + * Returns the ObjectFactory for root resource class and provider + * instantiation, if given. + * + * @return the ObjectFactory for root resource class and provider + * instantiation, if given. + */ + public ObjectFactory getObjectFactory() { + return this.jaxRsRouter.getObjectFactory(); + } + /** * Returns the current RoleChecker * @@ -337,6 +348,18 @@ public void setGuard(Guard guard) { this.guard = guard; } + /** + * Sets the ObjectFactory for root resource class and provider + * instantiation. + * + * @param objectFactory + * the ObjectFactory for root resource class and provider + * instantiation. + */ + public void setObjectFactory(ObjectFactory objectFactory) { + this.jaxRsRouter.setObjectFactory(objectFactory); + } + /** * Some browsers (e.g. Internet Explorer 7.0 and Firefox 2.0) sends as * accepted media type XML with a higher quality than HTML. The consequence diff --git a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/JaxRsRouter.java b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/JaxRsRouter.java index 44ce111066..e0249faad5 100644 --- a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/JaxRsRouter.java +++ b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/JaxRsRouter.java @@ -166,6 +166,8 @@ public class JaxRsRouter extends Restlet { @SuppressWarnings(""unchecked"") private final ThreadLocalizedContext tlContext = new ThreadLocalizedContext(); + private volatile ObjectFactory objectFactory; + /** * Creates a new JaxRsRouter with the given Context. Only the default * providers are loaded. If a resource class later wants to check if a user @@ -330,8 +332,9 @@ private boolean addProvider(Class jaxRsProviderClass, } Provider provider; try { - provider = new Provider(jaxRsProviderClass, tlContext, - this.entityProviders, contextResolvers, getLogger()); + provider = new Provider(jaxRsProviderClass, objectFactory, + tlContext, this.entityProviders, contextResolvers, + getLogger()); } catch (InstantiateException e) { String msg = ""Ignore provider "" + jaxRsProviderClass.getName() + ""Could not instantiate the Provider, class "" @@ -507,7 +510,7 @@ private ResourceObject instantiateRrc(RootResourceClass rrc) throws WebApplicationException, RequestHandledException { ResourceObject o; try { - o = rrc.createInstance(); + o = rrc.createInstance(this.objectFactory); } catch (WebApplicationException e) { throw e; } catch (RuntimeException e) { @@ -1078,4 +1081,27 @@ public Collection getRootUris() { uris.add(rrc.getPathRegExp().getPathPattern()); return Collections.unmodifiableCollection(uris); } + + /** + * Returns the ObjectFactory for root resource class and provider + * instantiation, if given. + * + * @return the ObjectFactory for root resource class and provider + * instantiation, if given. + */ + public ObjectFactory getObjectFactory() { + return this.objectFactory; + } + + /** + * Sets the ObjectFactory for root resource class and provider + * instantiation. + * + * @param objectFactory + * the ObjectFactory for root resource class and provider + * instantiation. + */ + public void setObjectFactory(ObjectFactory objectFactory) { + this.objectFactory = objectFactory; + } } \ No newline at end of file diff --git a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/ObjectFactory.java b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/ObjectFactory.java new file mode 100644 index 0000000000..dc4e8134a4 --- /dev/null +++ b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/ObjectFactory.java @@ -0,0 +1,53 @@ +/* + * Copyright 2005-2008 Noelios Consulting. + * + * The contents of this file are subject to the terms of the Common Development + * and Distribution License (the ""License""). You may not use this file except in + * compliance with the License. + * + * You can obtain a copy of the license at + * http://www.opensource.org/licenses/cddl1.txt See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each file and + * include the License file at http://www.opensource.org/licenses/cddl1.txt If + * applicable, add the following below this CDDL HEADER, with the fields + * enclosed by brackets ""[]"" replaced with your own identifying information: + * Portions Copyright [yyyy] [name of copyright owner] + */ +package org.restlet.ext.jaxrs; + +import org.restlet.ext.jaxrs.internal.exceptions.InstantiateException; + +/** + *

+ * Implement this interface to instantiate JAX-RS root resource classes and + * providers yourself and register it by + * {@link JaxRsApplication#setObjectFactory(ObjectFactory)}. + *

+ * + *

+ * When using a ObjectFactory, no JAX-RS constructor dependency injection will + * be performed, but instance variable and bean setter injection will still be + * done. + *

+ * + * @author Bruno Dumon + * @see JaxRsApplication#setObjectFactory(ObjectFactory) + * @see JaxRsRouter#setObjectFactory(ObjectFactory) + */ +public interface ObjectFactory { + /** + * Creates an instance of the given class.
+ * If the concrete instance could not instantiate the given class, it could + * return null. Than the constructor specified by the JAX-RS specification + * (section 4.2) is used. + * + * @param + * @param jaxRsClass + * the root resource class or provider class. + * @return + * @throws InstantiateException + */ + public T getInstance(Class jaxRsClass) throws InstantiateException; +} \ No newline at end of file diff --git a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/internal/wrappers/RootResourceClass.java b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/internal/wrappers/RootResourceClass.java index 2957fc6c68..08dd0ae0dc 100644 --- a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/internal/wrappers/RootResourceClass.java +++ b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/internal/wrappers/RootResourceClass.java @@ -28,6 +28,7 @@ import javax.ws.rs.ext.ContextResolver; import org.restlet.ext.jaxrs.JaxRsRouter; +import org.restlet.ext.jaxrs.ObjectFactory; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.ConvertRepresentationException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnClassException; @@ -122,22 +123,28 @@ private static void checkClassForPathAnnot(Class jaxRsClass, /** * Creates an instance of the root resource class. * + * @param objectFactory + * object responsible for instantiating the root resource + * class. Optional, thus can be null. * @return * @throws InvocationTargetException * @throws InstantiateException * @throws MissingAnnotationException * @throws WebApplicationException */ - public ResourceObject createInstance() throws InstantiateException, - InvocationTargetException { - Constructor constructor = this.constructor; - Object instance; - try { - instance = WrapperUtil.createInstance(constructor, - constructorParameters.get()); - } catch (ConvertRepresentationException e) { - // is not possible - throw new ImplementationException(""Must not be possible"", e); + public ResourceObject createInstance(ObjectFactory objectFactory) + throws InstantiateException, InvocationTargetException { + Object instance = null; + if (objectFactory != null) + instance = objectFactory.getInstance(jaxRsClass); + if (instance == null) { + try { + Object[] args = constructorParameters.get(); + instance = WrapperUtil.createInstance(constructor, args); + } catch (ConvertRepresentationException e) { + // is not possible + throw new ImplementationException(""Must not be possible"", e); + } } ResourceObject rootResourceObject = new ResourceObject(instance, this); try { diff --git a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/internal/wrappers/provider/Provider.java b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/internal/wrappers/provider/Provider.java index 1fa634f510..b42e36bc61 100644 --- a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/internal/wrappers/provider/Provider.java +++ b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/internal/wrappers/provider/Provider.java @@ -40,6 +40,7 @@ import javax.ws.rs.ext.MessageBodyWorkers; import org.restlet.data.MediaType; +import org.restlet.ext.jaxrs.ObjectFactory; import org.restlet.ext.jaxrs.internal.core.CallContext; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.ConvertCookieParamException; @@ -101,6 +102,9 @@ public class Provider implements MessageBodyReader, MessageBodyWriter, * * @param jaxRsProviderClass * the JAX-RS provider class. + * @param objectFactory + * The object factory is responsible for the provider + * instantiation, if given. * @param tlContext * The tread local wrapped call context * @param mbWorkers @@ -124,7 +128,7 @@ public class Provider implements MessageBodyReader, MessageBodyWriter, * @see javax.ws.rs.ext.ContextResolver */ @SuppressWarnings(""unchecked"") - public Provider(Class jaxRsProviderClass, + public Provider(Class jaxRsProviderClass, ObjectFactory objectFactory, ThreadLocalizedContext tlContext, EntityProviders mbWorkers, Collection> allResolvers, Logger logger) throws IllegalArgumentException, InvocationTargetException, @@ -134,10 +138,15 @@ public Provider(Class jaxRsProviderClass, throw new IllegalArgumentException( ""The JAX-RS provider class must not be null""); Util.checkClassConcrete(jaxRsProviderClass, ""provider""); - Constructor providerConstructor = WrapperUtil.findJaxRsConstructor( - jaxRsProviderClass, ""provider""); - this.jaxRsProvider = createInstance(providerConstructor, - jaxRsProviderClass, tlContext, mbWorkers, allResolvers, logger); + if (objectFactory != null) + this.jaxRsProvider = objectFactory.getInstance(jaxRsProviderClass); + if (this.jaxRsProvider == null) { + Constructor providerConstructor = WrapperUtil + .findJaxRsConstructor(jaxRsProviderClass, ""provider""); + this.jaxRsProvider = createInstance(providerConstructor, + jaxRsProviderClass, tlContext, mbWorkers, allResolvers, + logger); + } boolean isProvider = false; if (jaxRsProvider instanceof javax.ws.rs.ext.MessageBodyWriter) { this.writer = (javax.ws.rs.ext.MessageBodyWriter) jaxRsProvider;" e54358472c94d63c66ad607be256f94378e8ff16,orientdb,Issue -2900,c,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseBinary.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseBinary.java deleted file mode 100644 index 2ec9a2144fb..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseBinary.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * - * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com) - * * - * * Licensed under the Apache License, Version 2.0 (the ""License""); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an ""AS IS"" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://www.orientechnologies.com - * - */ -package com.orientechnologies.orient.core.db.record; - -import com.orientechnologies.orient.core.record.impl.ORecordBytes; - -/** - * Binary specialization of transactional database. - * - */ -public class ODatabaseBinary extends ODatabaseRecordTx { - - public ODatabaseBinary(String iURL) { - super(iURL, ORecordBytes.RECORD_TYPE); - } -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseFlat.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseFlat.java deleted file mode 100755 index 09bc14dfc99..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseFlat.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * - * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com) - * * - * * Licensed under the Apache License, Version 2.0 (the ""License""); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an ""AS IS"" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://www.orientechnologies.com - * - */ -package com.orientechnologies.orient.core.db.record; - -import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.iterator.ORecordIteratorCluster; -import com.orientechnologies.orient.core.record.impl.ORecordFlat; - -/** - * Delegates all the CRUD operations to the current transaction. - * - */ -public class ODatabaseFlat extends ODatabaseRecordTx { - - public ODatabaseFlat(String iURL) { - super(iURL, ORecordFlat.RECORD_TYPE); - serializer = ODatabaseDocumentTx.getDefaultSerializer(); - } - - @SuppressWarnings(""unchecked"") - @Override - public ORecordIteratorCluster browseCluster(final String iClusterName) { - return super.browseCluster(iClusterName, ORecordFlat.class); - } - - @Override - public ORecordIteratorCluster browseCluster(String iClusterName, long startClusterPosition, - long endClusterPosition, boolean loadTombstones) { - return super.browseCluster(iClusterName, ORecordFlat.class, startClusterPosition, endClusterPosition, loadTombstones); - } - - @SuppressWarnings(""unchecked"") - @Override - public ORecordFlat newInstance() { - return new ORecordFlat(); - } -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/impl/ORecordFlat.java b/core/src/main/java/com/orientechnologies/orient/core/record/impl/ORecordFlat.java index 6db8b2e689b..b4701b13e49 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/record/impl/ORecordFlat.java +++ b/core/src/main/java/com/orientechnologies/orient/core/record/impl/ORecordFlat.java @@ -20,7 +20,7 @@ package com.orientechnologies.orient.core.record.impl; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; -import com.orientechnologies.orient.core.db.record.ODatabaseFlat; +import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.db.record.ODatabaseRecord; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.id.ORecordId; @@ -39,7 +39,7 @@ public class ORecordFlat extends ORecordAbstract implements ORecordStringable { public static final byte RECORD_TYPE = 'f'; protected String value; - public ORecordFlat(ODatabaseFlat iDatabase) { + public ORecordFlat(ODatabaseDocumentTx iDatabase) { this(); ODatabaseRecordThreadLocal.INSTANCE.set(iDatabase); } diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDFlatPhysicalTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDFlatPhysicalTest.java index 4bd522343d3..7e413faab08 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDFlatPhysicalTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDFlatPhysicalTest.java @@ -18,18 +18,18 @@ import java.util.HashSet; import java.util.Set; -import com.orientechnologies.orient.core.storage.OStorage; +import com.orientechnologies.orient.core.db.record.ODatabaseRecordAbstract; +import com.orientechnologies.orient.core.iterator.ORecordIteratorCluster; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; -import com.orientechnologies.orient.core.db.record.ODatabaseFlat; import com.orientechnologies.orient.core.record.impl.ORecordFlat; @Test(groups = { ""crud"", ""record-csv"" }, sequential = true) -public class CRUDFlatPhysicalTest extends FlatDBBaseTest { +public class CRUDFlatPhysicalTest extends DocumentDBBaseTest { private static final String CLUSTER_NAME = ""binary""; protected static final int TOT_RECORDS = 100; @@ -41,16 +41,16 @@ public CRUDFlatPhysicalTest(@Optional String url) { super(url); } - @BeforeClass - @Override - public void beforeClass() throws Exception { - super.beforeClass(); - record = database.newInstance(); - } + @BeforeClass + @Override + public void beforeClass() throws Exception { + super.beforeClass(); + record = new ORecordFlat(); + } - public void createRaw() { - if (database.getClusterIdByName(CLUSTER_NAME) < 0) - database.addCluster(CLUSTER_NAME); + public void createRaw() { + if (database.getClusterIdByName(CLUSTER_NAME) < 0) + database.addCluster(CLUSTER_NAME); startRecordNumber = database.countClusterElements(CLUSTER_NAME); @@ -73,7 +73,8 @@ public void readRawWithExpressiveForwardIterator() { for (int i = 0; i < TOT_RECORDS; i++) ids.add(i); - for (ORecordFlat rec : database.browseCluster(CLUSTER_NAME)) { + for (ORecordFlat rec : new ORecordIteratorCluster(database, (ODatabaseRecordAbstract) database.getUnderlying(), + database.getClusterIdByName(CLUSTER_NAME), true)) { fields = rec.value().split(""-""); int i = Integer.parseInt(fields[0]); @@ -87,7 +88,8 @@ public void readRawWithExpressiveForwardIterator() { public void updateRaw() { String[] fields; - for (ORecordFlat rec : database.browseCluster(CLUSTER_NAME)) { + for (ORecordFlat rec : new ORecordIteratorCluster(database, (ODatabaseRecordAbstract) database.getUnderlying(), + database.getClusterIdByName(CLUSTER_NAME), true)) { fields = rec.value().split(""-""); int i = Integer.parseInt(fields[0]); if (i % 2 == 0) { @@ -105,7 +107,8 @@ public void testUpdateRaw() { for (int i = 0; i < TOT_RECORDS; i++) ids.add(i); - for (ORecordFlat rec : database.browseCluster(CLUSTER_NAME)) { + for (ORecordFlat rec : new ORecordIteratorCluster(database, (ODatabaseRecordAbstract) database.getUnderlying(), + database.getClusterIdByName(CLUSTER_NAME), true)) { fields = rec.value().split(""-""); int i = Integer.parseInt(fields[0]); diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/DictionaryTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/DictionaryTest.java index a4c3c2ad1a4..54383db3c65 100755 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/DictionaryTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/DictionaryTest.java @@ -23,7 +23,6 @@ import org.testng.annotations.Test; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.db.record.ODatabaseFlat; import com.orientechnologies.orient.core.record.ORecord; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.record.impl.ORecordFlat; @@ -40,49 +39,32 @@ public DictionaryTest(@Optional String url) { } public void testDictionaryCreate() throws IOException { - ODatabaseFlat database = new ODatabaseFlat(url); - database.open(""admin"", ""admin""); - ORecordFlat record = database.newInstance(); + ORecordFlat record = new ORecordFlat(); database.getDictionary().put(""key1"", record.value(""Dictionary test!"")); - - database.close(); } @Test(dependsOnMethods = ""testDictionaryCreate"") public void testDictionaryLookup() throws IOException { - ODatabaseFlat database = new ODatabaseFlat(url); - database.open(""admin"", ""admin""); - Assert.assertNotNull(database.getDictionary().get(""key1"")); Assert.assertTrue(((ORecordFlat) database.getDictionary().get(""key1"")).value().equals(""Dictionary test!"")); - - database.close(); } @Test(dependsOnMethods = ""testDictionaryLookup"") public void testDictionaryUpdate() throws IOException { - ODatabaseFlat database = new ODatabaseFlat(url); - database.open(""admin"", ""admin""); - final long originalSize = database.getDictionary().size(); - database.getDictionary().put(""key1"", database.newInstance().value(""Text changed"")); + database.getDictionary().put(""key1"", new ORecordFlat().value(""Text changed"")); database.close(); database.open(""admin"", ""admin""); Assert.assertEquals(((ORecordFlat) database.getDictionary().get(""key1"")).value(), ""Text changed""); Assert.assertEquals(database.getDictionary().size(), originalSize); - - database.close(); } @Test(dependsOnMethods = ""testDictionaryUpdate"") public void testDictionaryDelete() throws IOException { - ODatabaseFlat database = new ODatabaseFlat(url); - database.open(""admin"", ""admin""); - final long originalSize = database.getDictionary().size(); Assert.assertNotNull(database.getDictionary().remove(""key1"")); @@ -90,22 +72,17 @@ public void testDictionaryDelete() throws IOException { database.open(""admin"", ""admin""); Assert.assertEquals(database.getDictionary().size(), originalSize - 1); - - database.close(); } @Test(dependsOnMethods = ""testDictionaryDelete"") public void testDictionaryMassiveCreate() throws IOException { - ODatabaseFlat database = new ODatabaseFlat(url); - database.open(""admin"", ""admin""); - final long originalSize = database.getDictionary().size(); // ASSURE TO STORE THE PAGE-SIZE + 3 FORCING THE CREATION OF LEFT AND RIGHT final int total = 1000; for (int i = total; i > 0; --i) { - database.getDictionary().put(""key-"" + (originalSize + i), database.newInstance().value(""test-dictionary-"" + i)); + database.getDictionary().put(""key-"" + (originalSize + i), new ORecordFlat().value(""test-dictionary-"" + i)); } for (int i = total; i > 0; --i) { @@ -114,22 +91,15 @@ public void testDictionaryMassiveCreate() throws IOException { } Assert.assertEquals(database.getDictionary().size(), originalSize + total); - - database.close(); } @Test(dependsOnMethods = ""testDictionaryMassiveCreate"") public void testDictionaryInTx() throws IOException { - ODatabaseFlat database = new ODatabaseFlat(url); - database.open(""admin"", ""admin""); - database.begin(); - database.getDictionary().put(""tx-key"", database.newInstance().value(""tx-test-dictionary"")); + database.getDictionary().put(""tx-key"", new ORecordFlat().value(""tx-test-dictionary"")); database.commit(); Assert.assertNotNull(database.getDictionary().get(""tx-key"")); - - database.close(); } public class ObjectDictionaryTest { diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/FlatDBBaseTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/FlatDBBaseTest.java deleted file mode 100644 index fe45fa706d6..00000000000 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/FlatDBBaseTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.orientechnologies.orient.test.database.auto; - -import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.db.record.ODatabaseFlat; -import org.testng.annotations.Optional; -import org.testng.annotations.Parameters; - -/** - * @author Andrey Lomakin Andrey Lomakin - * @since 7/10/14 - */ -public abstract class FlatDBBaseTest extends BaseTest { - @Parameters(value = ""url"") - protected FlatDBBaseTest(@Optional String url) { - super(url); - } - - @Override - protected ODatabaseFlat createDatabaseInstance(String url) { - return new ODatabaseFlat(url); - } - - @Override - protected void createDatabase() { - ODatabaseDocumentTx db = new ODatabaseDocumentTx(database.getURL()); - db.create(); - db.close(); - - database.open(""admin"", ""admin""); - } -} diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionAtomicTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionAtomicTest.java index 391133364b1..e06eef77857 100755 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionAtomicTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionAtomicTest.java @@ -25,7 +25,6 @@ import com.orientechnologies.orient.core.db.ODatabase; import com.orientechnologies.orient.core.db.ODatabaseListener; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.db.record.ODatabaseFlat; import com.orientechnologies.orient.core.exception.OConcurrentModificationException; import com.orientechnologies.orient.core.exception.OTransactionException; import com.orientechnologies.orient.core.metadata.schema.OClass; @@ -45,13 +44,13 @@ public TransactionAtomicTest(@Optional String url) { @Test public void testTransactionAtomic() throws IOException { - ODatabaseFlat db1 = new ODatabaseFlat(url); + ODatabaseDocumentTx db1 = new ODatabaseDocumentTx(url); db1.open(""admin"", ""admin""); - ODatabaseFlat db2 = new ODatabaseFlat(url); + ODatabaseDocumentTx db2 = new ODatabaseDocumentTx(url); db2.open(""admin"", ""admin""); - ORecordFlat record1 = new ORecordFlat(db1); + ORecordFlat record1 = new ORecordFlat(); record1.value(""This is the first version"").save(); // RE-READ THE RECORD @@ -91,7 +90,7 @@ public void testMVCC() throws IOException { @Test(expectedExceptions = OTransactionException.class) public void testTransactionPreListenerRollback() throws IOException { - ODatabaseFlat db = new ODatabaseFlat(url); + ODatabaseDocumentTx db = new ODatabaseDocumentTx(url); db.open(""admin"", ""admin""); ORecordFlat record1 = new ORecordFlat(db); diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/CreateRelationshipsSpeedTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/CreateRelationshipsSpeedTest.java index 080197a4492..5c9b0944325 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/CreateRelationshipsSpeedTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/CreateRelationshipsSpeedTest.java @@ -19,12 +19,11 @@ import java.io.UnsupportedEncodingException; import com.orientechnologies.common.test.SpeedTestMonoThread; -import com.orientechnologies.orient.core.db.record.ODatabaseFlat; +import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.record.impl.ORecordFlat; -import com.orientechnologies.orient.core.storage.OStorage; public class CreateRelationshipsSpeedTest extends SpeedTestMonoThread { - private ODatabaseFlat database; + private ODatabaseDocumentTx database; private ORecordFlat record; public CreateRelationshipsSpeedTest() { diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/DictionaryLookupInverseSpeedTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/DictionaryLookupInverseSpeedTest.java index 095137fffe6..a94eddda3a0 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/DictionaryLookupInverseSpeedTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/DictionaryLookupInverseSpeedTest.java @@ -17,17 +17,17 @@ import java.io.UnsupportedEncodingException; +import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import org.testng.Assert; import org.testng.annotations.Test; import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.db.record.ODatabaseFlat; import com.orientechnologies.orient.core.record.impl.ORecordFlat; import com.orientechnologies.orient.test.database.base.OrientMonoThreadTest; @Test(enabled = false) public class DictionaryLookupInverseSpeedTest extends OrientMonoThreadTest { - private ODatabaseFlat database; + private ODatabaseDocumentTx database; public static void main(String[] iArgs) throws InstantiationException, IllegalAccessException { DictionaryLookupInverseSpeedTest test = new DictionaryLookupInverseSpeedTest(); @@ -37,7 +37,7 @@ public static void main(String[] iArgs) throws InstantiationException, IllegalAc public DictionaryLookupInverseSpeedTest() { super(100000); Orient.instance().getProfiler().startRecording(); - database = new ODatabaseFlat(System.getProperty(""url"")).open(""admin"", ""admin""); + database = new ODatabaseDocumentTx(System.getProperty(""url"")).open(""admin"", ""admin""); } @Override diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/DictionaryLookupSpeedTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/DictionaryLookupSpeedTest.java index 8a660404859..fd1b3dd6610 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/DictionaryLookupSpeedTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/DictionaryLookupSpeedTest.java @@ -17,17 +17,17 @@ import java.io.UnsupportedEncodingException; +import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import org.testng.Assert; import org.testng.annotations.Test; import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.db.record.ODatabaseFlat; import com.orientechnologies.orient.core.record.impl.ORecordFlat; import com.orientechnologies.orient.test.database.base.OrientMonoThreadTest; @Test(enabled = false) public class DictionaryLookupSpeedTest extends OrientMonoThreadTest { - private ODatabaseFlat database; + private ODatabaseDocumentTx database; public static void main(String[] iArgs) throws InstantiationException, IllegalAccessException { DictionaryLookupSpeedTest test = new DictionaryLookupSpeedTest(); @@ -37,7 +37,7 @@ public static void main(String[] iArgs) throws InstantiationException, IllegalAc public DictionaryLookupSpeedTest() { super(100000); Orient.instance().getProfiler().startRecording(); - database = new ODatabaseFlat(System.getProperty(""url"")).open(""admin"", ""admin""); + database = new ODatabaseDocumentTx(System.getProperty(""url"")).open(""admin"", ""admin""); } @Override diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/DictionaryPutSpeedTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/DictionaryPutSpeedTest.java index ab7d510ef1e..684a385244a 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/DictionaryPutSpeedTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/DictionaryPutSpeedTest.java @@ -15,10 +15,10 @@ */ package com.orientechnologies.orient.test.database.speed; +import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import org.testng.annotations.Test; import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.db.record.ODatabaseFlat; import com.orientechnologies.orient.core.intent.OIntentMassiveInsert; import com.orientechnologies.orient.core.record.impl.ORecordFlat; import com.orientechnologies.orient.core.tx.OTransaction.TXTYPE; @@ -26,7 +26,7 @@ @Test(enabled = false) public class DictionaryPutSpeedTest extends OrientMonoThreadTest { - private ODatabaseFlat database; + private ODatabaseDocumentTx database; private ORecordFlat record; private long startNum; @@ -40,10 +40,10 @@ public DictionaryPutSpeedTest() throws InstantiationException, IllegalAccessExce super(1000000); String url = System.getProperty(""url""); - database = new ODatabaseFlat(url).open(""admin"", ""admin""); + database = new ODatabaseDocumentTx(url).open(""admin"", ""admin""); database.declareIntent(new OIntentMassiveInsert()); - record = database.newInstance(); + record = new ORecordFlat(); startNum = 0;// database.countClusterElements(""Animal""); Orient.instance().getProfiler().startRecording(); diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/LocalCreateBinarySpeedTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/LocalCreateBinarySpeedTest.java index 7c2c3de9567..711877b3895 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/LocalCreateBinarySpeedTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/LocalCreateBinarySpeedTest.java @@ -17,10 +17,10 @@ import java.util.Random; +import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import org.testng.annotations.Test; import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.db.record.ODatabaseFlat; import com.orientechnologies.orient.core.intent.OIntentMassiveInsert; import com.orientechnologies.orient.core.record.impl.ORecordBytes; import com.orientechnologies.orient.core.tx.OTransaction.TXTYPE; @@ -28,7 +28,7 @@ @Test(enabled = false) public class LocalCreateBinarySpeedTest extends OrientMonoThreadTest { - private ODatabaseFlat database; + private ODatabaseDocumentTx database; private ORecordBytes record; private final static int RECORD_SIZE = 512; private byte[] recordContent; @@ -46,7 +46,7 @@ public LocalCreateBinarySpeedTest() throws InstantiationException, IllegalAccess public void init() { Orient.instance().getProfiler().startRecording(); - database = new ODatabaseFlat(System.getProperty(""url"")).open(""admin"", ""admin""); + database = new ODatabaseDocumentTx(System.getProperty(""url"")).open(""admin"", ""admin""); record = new ORecordBytes(); database.declareIntent(new OIntentMassiveInsert()); diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/LocalCreateFlatMultiThreadSpeedTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/LocalCreateFlatMultiThreadSpeedTest.java index 80196ce13b2..36d663b78f8 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/LocalCreateFlatMultiThreadSpeedTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/LocalCreateFlatMultiThreadSpeedTest.java @@ -15,11 +15,11 @@ */ package com.orientechnologies.orient.test.database.speed; +import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import org.testng.Assert; import org.testng.annotations.Test; import com.orientechnologies.common.test.SpeedTestMultiThreads; -import com.orientechnologies.orient.core.db.record.ODatabaseFlat; import com.orientechnologies.orient.core.intent.OIntentMassiveInsert; import com.orientechnologies.orient.core.record.impl.ORecordFlat; import com.orientechnologies.orient.core.tx.OTransaction.TXTYPE; @@ -28,12 +28,12 @@ @Test(enabled = false) public class LocalCreateFlatMultiThreadSpeedTest extends OrientMultiThreadTest { - protected ODatabaseFlat database; + protected ODatabaseDocumentTx database; private long foundObjects; @Test(enabled = false) public static class CreateObjectsThread extends OrientThreadTest { - protected ODatabaseFlat database; + protected ODatabaseDocumentTx database; protected ORecordFlat record; public CreateObjectsThread(final SpeedTestMultiThreads parent, final int threadId) { @@ -42,8 +42,8 @@ public CreateObjectsThread(final SpeedTestMultiThreads parent, final int threadI @Override public void init() { - database = new ODatabaseFlat(System.getProperty(""url"")).open(""admin"", ""admin""); - record = database.newInstance(); + database = new ODatabaseDocumentTx(System.getProperty(""url"")).open(""admin"", ""admin""); + record = new ORecordFlat(); database.declareIntent(new OIntentMassiveInsert()); database.begin(TXTYPE.NOTX); } @@ -75,7 +75,7 @@ public static void main(String[] iArgs) throws InstantiationException, IllegalAc @Override public void init() { - database = new ODatabaseFlat(System.getProperty(""url"")).open(""admin"", ""admin""); + database = new ODatabaseDocumentTx(System.getProperty(""url"")).open(""admin"", ""admin""); foundObjects = database.countClusterElements(""flat""); System.out.println(""\nTotal objects in Animal cluster before the test: "" + foundObjects); diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/LocalCreateFlatSpeedTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/LocalCreateFlatSpeedTest.java index 11efd77aefa..800a7eaa423 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/LocalCreateFlatSpeedTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/LocalCreateFlatSpeedTest.java @@ -15,11 +15,11 @@ */ package com.orientechnologies.orient.test.database.speed; +import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import org.testng.annotations.Test; import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.config.OGlobalConfiguration; -import com.orientechnologies.orient.core.db.record.ODatabaseFlat; import com.orientechnologies.orient.core.intent.OIntentMassiveInsert; import com.orientechnologies.orient.core.record.impl.ORecordFlat; import com.orientechnologies.orient.core.tx.OTransaction.TXTYPE; @@ -27,7 +27,7 @@ @Test(enabled = false) public class LocalCreateFlatSpeedTest extends OrientMonoThreadTest { - private ODatabaseFlat database; + private ODatabaseDocumentTx database; private ORecordFlat record; private long date = System.currentTimeMillis(); @@ -45,13 +45,13 @@ public LocalCreateFlatSpeedTest() throws InstantiationException, IllegalAccessEx public void init() { Orient.instance().getProfiler().startRecording(); - database = new ODatabaseFlat(System.getProperty(""url"")); + database = new ODatabaseDocumentTx(System.getProperty(""url"")); if (database.exists()) database.open(""admin"", ""admin""); else database.create(); - record = database.newInstance(); + record = new ORecordFlat(); database.declareIntent(new OIntentMassiveInsert()); database.begin(TXTYPE.NOTX); diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/TxRemoteCreateFlatSpeedTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/TxRemoteCreateFlatSpeedTest.java index 3d843ccf822..ff0cbd611ab 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/TxRemoteCreateFlatSpeedTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/TxRemoteCreateFlatSpeedTest.java @@ -15,16 +15,16 @@ */ package com.orientechnologies.orient.test.database.speed; +import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import org.testng.annotations.Test; import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.db.record.ODatabaseFlat; import com.orientechnologies.orient.core.record.impl.ORecordFlat; import com.orientechnologies.orient.test.database.base.OrientMonoThreadTest; @Test(enabled = false) public class TxRemoteCreateFlatSpeedTest extends OrientMonoThreadTest { - private ODatabaseFlat database; + private ODatabaseDocumentTx database; private ORecordFlat record; public static void main(String[] iArgs) throws InstantiationException, IllegalAccessException { @@ -40,8 +40,8 @@ public TxRemoteCreateFlatSpeedTest() throws InstantiationException, IllegalAcces public void init() { Orient.instance().getProfiler().startRecording(); - database = new ODatabaseFlat(System.getProperty(""url"")).open(""admin"", ""admin""); - record = database.newInstance(); + database = new ODatabaseDocumentTx(System.getProperty(""url"")).open(""admin"", ""admin""); + record = new ORecordFlat(); database.begin(); } diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/TxRemoteCreateObjectsMultiThreadSpeedTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/TxRemoteCreateObjectsMultiThreadSpeedTest.java index a041b4f5281..3d3c316871c 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/TxRemoteCreateObjectsMultiThreadSpeedTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/TxRemoteCreateObjectsMultiThreadSpeedTest.java @@ -16,20 +16,19 @@ package com.orientechnologies.orient.test.database.speed; import com.orientechnologies.common.test.SpeedTestMultiThreads; -import com.orientechnologies.orient.core.db.record.ODatabaseFlat; +import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.record.impl.ORecordFlat; -import com.orientechnologies.orient.core.storage.OStorage; import com.orientechnologies.orient.core.tx.OTransaction.TXTYPE; import com.orientechnologies.orient.test.database.base.OrientMultiThreadTest; import com.orientechnologies.orient.test.database.base.OrientThreadTest; public class TxRemoteCreateObjectsMultiThreadSpeedTest extends OrientMultiThreadTest { - protected ODatabaseFlat database; - protected long foundObjects; + protected ODatabaseDocumentTx database; + protected long foundObjects; public static class CreateObjectsThread extends OrientThreadTest { - protected ODatabaseFlat database; - protected ORecordFlat record = new ORecordFlat(); + protected ODatabaseDocumentTx database; + protected ORecordFlat record = new ORecordFlat(); public CreateObjectsThread(final SpeedTestMultiThreads parent, final int threadId) { super(parent, threadId); @@ -37,8 +36,8 @@ public CreateObjectsThread(final SpeedTestMultiThreads parent, final int threadI @Override public void init() { - database = new ODatabaseFlat(System.getProperty(""url"")).open(""admin"", ""admin""); - record = database.newInstance(); + database = new ODatabaseDocumentTx(System.getProperty(""url"")).open(""admin"", ""admin""); + record = new ORecordFlat(); database.begin(TXTYPE.NOTX); } @@ -69,7 +68,7 @@ public static void main(String[] iArgs) throws InstantiationException, IllegalAc @Override public void init() { - database = new ODatabaseFlat(System.getProperty(""url"")).open(""admin"", ""admin""); + database = new ODatabaseDocumentTx(System.getProperty(""url"")).open(""admin"", ""admin""); if (!database.getStorage().getClusterNames().contains(""Animal"")) database.addCluster(""Animal""); diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/TxTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/TxTest.java index 151dad1d413..1a5ec437302 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/TxTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/TxTest.java @@ -17,22 +17,22 @@ import java.io.UnsupportedEncodingException; +import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import org.testng.annotations.Test; -import com.orientechnologies.orient.core.db.record.ODatabaseFlat; import com.orientechnologies.orient.core.record.impl.ORecordFlat; import com.orientechnologies.orient.core.tx.OTransaction.TXTYPE; import com.orientechnologies.orient.test.database.base.OrientMonoThreadTest; @Test(enabled = false) public class TxTest extends OrientMonoThreadTest { - private ODatabaseFlat database; + private ODatabaseDocumentTx database; private ORecordFlat record; public TxTest() throws InstantiationException, IllegalAccessException { super(10); - database = new ODatabaseFlat(System.getProperty(""url"")).open(""admin"", ""admin""); - record = database.newInstance(); + database = new ODatabaseDocumentTx(System.getProperty(""url"")).open(""admin"", ""admin""); + record = new ORecordFlat(); database.begin(TXTYPE.OPTIMISTIC); }" c3b4d70410f2acd2a7d6f3ef9fbcd2a156fe9f30,coremedia$jangaroo-tools,"Submit last night's results: * Correct handling of newlines inside generated strings (e.g. modifiers rendered inside string for the runtime to interpret). * Support *-imports. Not recommended, since it disables automatic class loading, but good for reusing existing ActionScript 3 libraries. * FlexUnit now compiles and runs with minimal changes: - added some missing semicolons - static members of super classes are not in scope - the super class and package-scoped methods still have to be imported explicitly - ArrayCollection not yet implemented - special case when subclassing native class Error [git-p4: depot-paths = ""//coremedia/jangaroo/"": change = 146563] ",a,https://github.com/coremedia/jangaroo-tools,"diff --git a/jooc/src/main/cup/net/jangaroo/jooc/joo.cup b/jooc/src/main/cup/net/jangaroo/jooc/joo.cup index e1169a5f1..5b504c150 100644 --- a/jooc/src/main/cup/net/jangaroo/jooc/joo.cup +++ b/jooc/src/main/cup/net/jangaroo/jooc/joo.cup @@ -229,6 +229,8 @@ classBody ::= classBodyDeclarations ::= {: RESULT = new ArrayList(); :} + | classBodyDeclarations:list directive:d + {: RESULT = list; :} | classBodyDeclarations:list classBodyDeclaration:decl {: RESULT = list; list.add(decl); :} ; @@ -269,6 +271,8 @@ constOrVar ::= directive ::= IMPORT:i qualifiedIde:ide SEMICOLON:s {: RESULT = new ImportDirective(i,new IdeType(ide), s); :} + | IMPORT:i qualifiedIde:ide DOT:dot MUL:all SEMICOLON:s + {: RESULT = new ImportDirective(i,new IdeType(new QualifiedIde(ide,dot,all)), s); :} | LBRACK:lb ide:ide RBRACK:rb {: RESULT = new Annotation(lb, ide, rb); :} | LBRACK:lb ide:ide LPAREN:lb2 annotationFields:af RPAREN:rb2 RBRACK:rb @@ -286,7 +290,7 @@ annotationField ::= ide:name EQ:eq expr:value {: RESULT = new ObjectField(new IdeExpr(name),eq,value); :} | expr:value - {: RESULT = new ObjectField(new IdeExpr(new Ide(new JooSymbol(""""))),null,value); :} + {: RESULT = new ObjectField(null,null,value); :} ; annotationFields ::= diff --git a/jooc/src/main/java/net/jangaroo/jooc/ApplyExpr.java b/jooc/src/main/java/net/jangaroo/jooc/ApplyExpr.java index 39e17a443..857549d14 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/ApplyExpr.java +++ b/jooc/src/main/java/net/jangaroo/jooc/ApplyExpr.java @@ -22,6 +22,9 @@ */ class ApplyExpr extends Expr { + // TODO: add a compiler option for this: + public static final boolean ASSUME_UNDECLARED_UPPER_CASE_FUNCTIONS_CALLS_ARE_TYPE_CASTS = Boolean.valueOf(""true""); + Expr fun; boolean isType; JooSymbol lParen; @@ -63,9 +66,9 @@ public void analyze(Node parentNode, AnalyzeContext context) { // otherwise, it is most likely an imported package-namespaced function. if (Character.isUpperCase(funIde.getName().charAt(0))) { Scope scope = context.getScope().findScopeThatDeclares(funIde); - if (scope!=null) { - isType = scope.getDeclaration()==context.getScope().getPackageDeclaration(); - } + isType = scope == null + ? ASSUME_UNDECLARED_UPPER_CASE_FUNCTIONS_CALLS_ARE_TYPE_CASTS + : scope.getDeclaration() == context.getScope().getPackageDeclaration(); } } fun.analyze(this, context); diff --git a/jooc/src/main/java/net/jangaroo/jooc/ClassDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/ClassDeclaration.java index 9797a8188..a2d5f048d 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/ClassDeclaration.java +++ b/jooc/src/main/java/net/jangaroo/jooc/ClassDeclaration.java @@ -28,6 +28,7 @@ public class ClassDeclaration extends IdeDeclaration { private Map members = new LinkedHashMap(); private Set boundMethodCandidates = new HashSet(); private Set classInit = new HashSet(); + private List packageImports; public Extends getOptExtends() { return optExtends; @@ -88,15 +89,14 @@ public void setConstructor(MethodDeclaration methodDeclaration) { } public void generateCode(JsWriter out) throws IOException { - out.writeSymbolWhitespace(symClass); - if (!writeRuntimeModifiersUnclosed(out)) { - out.write(""\""""); - } - out.writeSymbolToken(symClass); + out.beginString(); + writeModifiers(out); + out.writeSymbol(symClass); ide.generateCode(out); if (optExtends != null) optExtends.generateCode(out); if (optImplements != null) optImplements.generateCode(out); - out.write(""\"",[""); + out.endString(); + out.write("",[""); boolean isFirst = true; for (MemberDeclaration memberDeclaration : members.values()) { if (memberDeclaration.isMethod() && memberDeclaration.isPublic() && memberDeclaration.isStatic()) { @@ -111,7 +111,12 @@ public void generateCode(JsWriter out) throws IOException { } } out.write(""],""); - out.write(""function($jooPublic,$jooPrivate){with($jooPublic)with($jooPrivate)return[""); + String packageName = QualifiedIde.constructQualifiedNameStr(getPackageDeclaration().getQualifiedName()); + out.write(""function($jooPublic,$jooPrivate){""); + for (String importedPackage : packageImports) { + out.write(""with(""+importedPackage+"")""); + } + out.write(""with(""+ packageName +"")with($jooPublic)with($jooPrivate)return[""); if (!classInit.isEmpty()) { out.write(""function(){joo.Class.init(""); for (Iterator iterator = classInit.iterator(); iterator.hasNext();) { @@ -129,6 +134,7 @@ public void generateCode(JsWriter out) throws IOException { public void analyze(Node parentNode, AnalyzeContext context) { // do *not* call super! this.parentNode = parentNode; + packageImports = context.getCurrentPackage().getPackageImports(); context.getScope().declareIde(getName(), this); parentDeclaration = context.getScope().getPackageDeclaration(); context.enterScope(this); diff --git a/jooc/src/main/java/net/jangaroo/jooc/Declaration.java b/jooc/src/main/java/net/jangaroo/jooc/Declaration.java index e5f11d767..05e4edefb 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/Declaration.java +++ b/jooc/src/main/java/net/jangaroo/jooc/Declaration.java @@ -120,28 +120,6 @@ protected void writeModifiers(JsWriter out) throws IOException { } } - protected void writeRuntimeModifiers(JsWriter out) throws IOException { - if (writeRuntimeModifiersUnclosed(out)) { - out.write(""\"",""); - } - } - - protected boolean writeRuntimeModifiersUnclosed(JsWriter out) throws IOException { - if (symModifiers.length>0) { - out.writeSymbolWhitespace(symModifiers[0]); - out.write('""'); - for (int i = 0; i < symModifiers.length; i++) { - JooSymbol modifier = symModifiers[i]; - if (i==0) - out.writeSymbolToken(modifier); - else - out.writeSymbol(modifier); - } - return true; - } - return false; - } - public void analyze(Node parentNode, AnalyzeContext context) { super.analyze(parentNode, context); parentDeclaration = context.getScope().getDeclaration(); diff --git a/jooc/src/main/java/net/jangaroo/jooc/DotExpr.java b/jooc/src/main/java/net/jangaroo/jooc/DotExpr.java index d0374a329..cd92f9407 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/DotExpr.java +++ b/jooc/src/main/java/net/jangaroo/jooc/DotExpr.java @@ -48,10 +48,11 @@ public void analyze(Node parentNode, AnalyzeContext context) { if (!(parentNode instanceof ApplyExpr)) { String[] qualifiedName = getQualifiedName(arg1); if (qualifiedName!=null) { - String qulifiedNameStr = QualifiedIde.constructQualifiedNameStr(qualifiedName); - Scope declaringScope = context.getScope().findScopeThatDeclares(qulifiedNameStr); - if (declaringScope!=null && declaringScope.getDeclaration().equals(context.getCurrentPackage())) { - this.classDeclaration.addClassInit(qulifiedNameStr); + String qualifiedNameStr = QualifiedIde.constructQualifiedNameStr(qualifiedName); + Scope declaringScope = context.getScope().findScopeThatDeclares(qualifiedNameStr); + if (declaringScope==null && qualifiedNameStr.indexOf('.')==-1 && Character.isUpperCase(qualifiedNameStr.charAt(0)) + || declaringScope!=null && declaringScope.getDeclaration().equals(context.getCurrentPackage())) { + this.classDeclaration.addClassInit(qualifiedNameStr); } } } diff --git a/jooc/src/main/java/net/jangaroo/jooc/FieldDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/FieldDeclaration.java index 18d789af3..dc7db6fca 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/FieldDeclaration.java +++ b/jooc/src/main/java/net/jangaroo/jooc/FieldDeclaration.java @@ -35,13 +35,11 @@ public boolean isField() { } public void generateCode(JsWriter out) throws IOException { - out.writeSymbolWhitespace(optSymConstOrVar); - if (!writeRuntimeModifiersUnclosed(out)) { - out.write(""\""""); - } - out.writeSymbolToken(optSymConstOrVar); - out.write(""\"",""); - out.write('{'); + out.beginString(); + writeModifiers(out); + out.writeSymbol(optSymConstOrVar); + out.endString(); + out.write("",{""); generateIdeCode(out); if (optTypeRelation != null) optTypeRelation.generateCode(out); diff --git a/jooc/src/main/java/net/jangaroo/jooc/ImportDirective.java b/jooc/src/main/java/net/jangaroo/jooc/ImportDirective.java index aa142b060..b8be3237b 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/ImportDirective.java +++ b/jooc/src/main/java/net/jangaroo/jooc/ImportDirective.java @@ -37,9 +37,16 @@ public void analyze(Node parentNode, AnalyzeContext context) { super.analyze(parentNode, context); if (type instanceof IdeType) { Ide ide = ((IdeType)type).ide; - context.getScope().declareIde(ide.getName(), this); - // also add the fully qualified name (might be the same string for top level imports): - context.getScope().declareIde(QualifiedIde.constructQualifiedNameStr(ide.getQualifiedName()), this); + String typeName = ide.getName(); + if (""*"".equals(typeName)) { + // found *-import, do not register, but add to package import list: + String packageName = QualifiedIde.constructQualifiedNameStr(((QualifiedIde)ide).prefix.getQualifiedName()); + context.getCurrentPackage().addPackageImport(packageName); + } else { + context.getScope().declareIde(typeName, this); + // also add the fully qualified name (might be the same string for top level imports): + context.getScope().declareIde(QualifiedIde.constructQualifiedNameStr(ide.getQualifiedName()), this); + } } } diff --git a/jooc/src/main/java/net/jangaroo/jooc/JsWriter.java b/jooc/src/main/java/net/jangaroo/jooc/JsWriter.java index 28a606519..5e99d3ffa 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/JsWriter.java +++ b/jooc/src/main/java/net/jangaroo/jooc/JsWriter.java @@ -33,6 +33,8 @@ public class JsWriter extends FilterWriter { boolean inComment = false; int nOpenBeginComments = 0; char lastChar = ' '; + boolean inString = false; + int nOpenStrings = 0; public JsWriter(Writer target) { super(target); @@ -152,7 +154,7 @@ public void beginComment() throws IOException { nOpenBeginComments++; } - private final boolean shouldWrite() throws IOException { + private boolean shouldWrite() throws IOException { boolean result = keepSource || nOpenBeginComments == 0; if (result) { if (nOpenBeginComments > 0 && !inComment) { @@ -178,10 +180,65 @@ public void beginCommentWriteSymbol(JooSymbol symbol) throws IOException { writeSymbol(symbol); } + public void beginString() throws IOException { + nOpenStrings++; + } + + private void checkOpenString() throws IOException { + if (nOpenStrings > 0 && !inString) { + out.write('""'); + lastChar = '""'; + inString = true; + } + } + + private boolean checkCloseString() throws IOException { + if (inString) { + out.write('""'); + inString = false; + return true; + } + return false; + } + + public void endString() throws IOException { + Debug.assertTrue(nOpenStrings > 0, ""missing beginString() for endString()""); + nOpenStrings--; + if (nOpenStrings == 0) { + checkCloseString(); + } + } + + private void writeLinesInsideString(String ws) throws IOException { + String[] lines = ws.split(""\n"",-1); + for (int i = 0; i < lines.length-1; i++) { + String line = lines[i]; + if (line.length()>1) { + checkOpenString(); + write(line.substring(0,line.length()-1)); + write(""\\n""); + } + if(checkCloseString()) { + write(""+""); + } + write(""\n""); + } + String line = lines[lines.length - 1]; + if (line.length()>0) { + checkOpenString(); + write(line); + } + } + public void writeSymbolWhitespace(JooSymbol symbol) throws IOException { String ws = symbol.getWhitespace(); - if (keepSource) - write(ws); + if (keepSource) { + if (inString) { + writeLinesInsideString(ws); + } else { + write(ws); + } + } else if (keepLines) writeLines(ws); } @@ -192,8 +249,14 @@ protected void writeLines(String s) throws IOException { protected void writeLines(String s, int off, int len) throws IOException { int pos = off; - while ((pos = s.indexOf('\n', pos)+1) > 0 && pos < off+len+1) + while ((pos = s.indexOf('\n', pos)+1) > 0 && pos < off+len+1) { + if (inString) { + write(""\\n""); + checkCloseString(); + write('+'); + } write('\n'); + } } public void writeToken(String token) throws IOException { @@ -204,6 +267,7 @@ public void writeToken(String token) throws IOException { (lastChar == firstSymbolChar && ""=>= 0) || (firstSymbolChar == '=' && ""=>= 0)) write(' '); + checkOpenString(); write(text); } } diff --git a/jooc/src/main/java/net/jangaroo/jooc/MethodDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/MethodDeclaration.java index 11ecafe4a..b0f442645 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/MethodDeclaration.java +++ b/jooc/src/main/java/net/jangaroo/jooc/MethodDeclaration.java @@ -125,26 +125,27 @@ public void generateCode(JsWriter out) throws IOException { out.writeSymbol(symFunction); ide.generateCode(out); } else { - if (!writeRuntimeModifiersUnclosed(out)) - out.write(""\""""); - else - out.write("" ""); + out.beginString(); + writeModifiers(out); String methodName = ide.getName(); - out.write(methodName); - out.write(""\"",""); + if (!isConstructor && !isStatic() && classDeclaration.isBoundMethod(methodName)) { + out.writeToken(""bound""); + } + out.writeToken(methodName); + out.endString(); + out.write("",""); out.writeSymbol(symFunction); out.writeSymbolWhitespace(ide.ide); if (out.getKeepSource()) { - out.write("" ""); if (isConstructor) { // do not name the constructor initializer function like the class, or it will be called // instead of the constructor function generated by the runtime! So we prefix it with a ""$"". // The name is for debugging purposes only, anyway. - out.write(""$""+methodName); + out.writeToken(""$""+methodName); } else if (ide instanceof AccessorIde) { - out.write(((AccessorIde)ide).getFunctionName()); + out.writeToken(((AccessorIde)ide).getFunctionName()); } else { - out.write(methodName); + out.writeToken(methodName); } } } diff --git a/jooc/src/main/java/net/jangaroo/jooc/ObjectField.java b/jooc/src/main/java/net/jangaroo/jooc/ObjectField.java index 3831976b5..c02ab5d6a 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/ObjectField.java +++ b/jooc/src/main/java/net/jangaroo/jooc/ObjectField.java @@ -34,13 +34,17 @@ public ObjectField(Expr nameExpr, JooSymbol symColon, Expr value) { public void analyze(Node parentNode, AnalyzeContext context) { super.analyze(parentNode, context); - nameExpr.analyze(this, context); + if (nameExpr!=null) { + nameExpr.analyze(this, context); + } value.analyze(this, context); } public void generateCode(JsWriter out) throws IOException { - nameExpr.generateCode(out); - out.writeSymbol(symColon); + if (nameExpr!=null) { + nameExpr.generateCode(out); + out.writeSymbol(symColon); + } value.generateCode(out); } diff --git a/jooc/src/main/java/net/jangaroo/jooc/PackageDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/PackageDeclaration.java index f82eaaf8d..f0a343dd7 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/PackageDeclaration.java +++ b/jooc/src/main/java/net/jangaroo/jooc/PackageDeclaration.java @@ -16,6 +16,9 @@ package net.jangaroo.jooc; import java.io.IOException; +import java.util.List; +import java.util.ArrayList; +import java.util.Collections; /** * @author Andreas Gawecki @@ -23,6 +26,15 @@ public class PackageDeclaration extends IdeDeclaration { JooSymbol symPackage; + private List packageImports = new ArrayList(); + + public void addPackageImport(String packageName) { + packageImports.add(packageName); + } + + public List getPackageImports() { + return Collections.unmodifiableList(packageImports); + } public PackageDeclaration(JooSymbol symPackage, Ide ide) { super(new JooSymbol[0], 0, ide); @@ -30,12 +42,12 @@ public PackageDeclaration(JooSymbol symPackage, Ide ide) { } public void generateCode(JsWriter out) throws IOException { - out.writeSymbolWhitespace(symPackage); - out.write(""\""package ""); + out.beginString(); + out.writeSymbol(symPackage); if (ide!=null) { ide.generateCode(out); } - out.write(""\""""); + out.endString(); out.write("",""); } diff --git a/jooc/src/main/java/net/jangaroo/jooc/TopLevelIdeExpr.java b/jooc/src/main/java/net/jangaroo/jooc/TopLevelIdeExpr.java index 53a2ce32c..859ba12f0 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/TopLevelIdeExpr.java +++ b/jooc/src/main/java/net/jangaroo/jooc/TopLevelIdeExpr.java @@ -38,7 +38,7 @@ public void analyze(Node parentNode, AnalyzeContext context) { if (scope!=null) { Scope declaringScope = scope.findScopeThatDeclares(ide); if (declaringScope==null || declaringScope.getDeclaration() instanceof ClassDeclaration) { - synthesizedDotExpr = new DotExpr(new ThisExpr(new JooSymbol(""this"")), new JooSymbol("".""), ide); + synthesizedDotExpr = new DotExpr(new ThisExpr(new JooSymbol(""this"")), new JooSymbol("".""), new Ide(ide.ide)); synthesizedDotExpr.analyze(parentNode, context); } } @@ -59,25 +59,28 @@ private boolean addThis() { Scope declaringScope = scope.findScopeThatDeclares(ide); if (declaringScope==null) { // check for fully qualified ide: - IdeExpr currentExpr = this; + DotExpr currentDotExpr = synthesizedDotExpr; String ideName = ide.getName(); - while (declaringScope==null && currentExpr.parentNode instanceof DotExpr && ((DotExpr)currentExpr.parentNode).arg2 instanceof IdeExpr) { - currentExpr = (IdeExpr)((DotExpr)currentExpr.parentNode).arg2; - ideName += ""."" +currentExpr.ide.getName(); + while (currentDotExpr.parentNode instanceof DotExpr) { + currentDotExpr = (DotExpr)currentDotExpr.parentNode; + if (!(currentDotExpr.arg2 instanceof IdeExpr)) + break; + ideName += ""."" +((IdeExpr)currentDotExpr.arg2).ide.getName(); declaringScope = scope.findScopeThatDeclares(ideName); + if (declaringScope!=null) { + // it has been defined in the meantime or is an imported qualified identifier: + return false; + } } - if (declaringScope!=null) { - return false; - } - boolean probablyAType = Character.isUpperCase(ide.getName().charAt(0)); + boolean maybeInScope = Character.isUpperCase(ide.getName().charAt(0)); String warningMsg = ""Undeclared identifier: "" + ide.getName(); - if (probablyAType) { - warningMsg += "", assuming it is a top level type.""; + if (maybeInScope) { + warningMsg += "", assuming it is already in scope.""; } else if (ASSUME_UNDECLARED_IDENTIFIERS_ARE_MEMBERS) { warningMsg += "", assuming it is an inherited member.""; } Jooc.warning(ide.getSymbol(), warningMsg); - return !probablyAType && ASSUME_UNDECLARED_IDENTIFIERS_ARE_MEMBERS; + return !maybeInScope && ASSUME_UNDECLARED_IDENTIFIERS_ARE_MEMBERS; } else if (declaringScope.getDeclaration() instanceof ClassDeclaration) { MemberDeclaration memberDeclaration = (MemberDeclaration)declaringScope.getIdeDeclaration(ide); return !memberDeclaration.isStatic() && !memberDeclaration.isConstructor(); @@ -85,4 +88,5 @@ private boolean addThis() { } return false; } + } \ No newline at end of file diff --git a/jooc/src/main/js/joo/Class.js b/jooc/src/main/js/joo/Class.js index eca78a3ad..c97c163db 100644 --- a/jooc/src/main/js/joo/Class.js +++ b/jooc/src/main/js/joo/Class.js @@ -499,7 +499,7 @@ Function.prototype.bind = function(object) { var memberName = undefined; var modifiers; if (typeof members==""string"") { - modifiers = members.split("" ""); + modifiers = members.split(/\s+/); for (var j=0; j get_files (); } - public static delegate void CallbackMarshal (Object object, void* data, Arg[] args); + [CCode (has_target = false)] + public delegate void CallbackMarshal (Object object, void* data, Arg[] args); public delegate void ActionCallback (Action action); diff --git a/vapi/packages/tracker-indexer-module-1.0/tracker-indexer-module-1.0-custom.vala b/vapi/packages/tracker-indexer-module-1.0/tracker-indexer-module-1.0-custom.vala index 7f9752f4b3..f5cf696ead 100644 --- a/vapi/packages/tracker-indexer-module-1.0/tracker-indexer-module-1.0-custom.vala +++ b/vapi/packages/tracker-indexer-module-1.0/tracker-indexer-module-1.0-custom.vala @@ -138,26 +138,26 @@ namespace Tracker { namespace Module { [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"")] public delegate void FileFreeDataFunc (); - [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"")] - public static delegate void* FileGetDataFunc (string path); - [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"")] - public static delegate weak Tracker.Metadata FileGetMetadataFunc (Tracker.File file); - [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"")] - public static delegate weak string FileGetServiceTypeFunc (Tracker.File file); - [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"")] - public static delegate weak string FileGetText (Tracker.File path); - [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"")] - public static delegate void FileGetUriFunc (Tracker.File file, string dirname, string basename); - [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"")] - public static delegate bool FileIterContents (Tracker.File path); - [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"")] - public static delegate weak string GetDirectoriesFunc (); - [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"")] - public static delegate weak string GetNameFunc (); - [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"")] - public static delegate void Init (); - [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"")] - public static delegate void Shutdown (); + [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"", has_target = false)] + public delegate void* FileGetDataFunc (string path); + [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"", has_target = false)] + public delegate weak Tracker.Metadata FileGetMetadataFunc (Tracker.File file); + [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"", has_target = false)] + public delegate weak string FileGetServiceTypeFunc (Tracker.File file); + [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"", has_target = false)] + public delegate weak string FileGetText (Tracker.File path); + [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"", has_target = false)] + public delegate void FileGetUriFunc (Tracker.File file, string dirname, string basename); + [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"", has_target = false)] + public delegate bool FileIterContents (Tracker.File path); + [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"", has_target = false)] + public delegate weak string GetDirectoriesFunc (); + [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"", has_target = false)] + public delegate weak string GetNameFunc (); + [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"", has_target = false)] + public delegate void Init (); + [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"", has_target = false)] + public delegate void Shutdown (); [CCode (cheader_filename = ""tracker-1.0/libtracker-indexer/tracker-module.h"")] public static void file_free_data (void* file_data);" dc9e9cb4cc87f132a32a00e6589d807350f0b8e0,elasticsearch,Aggregations: change to default shard_size in- terms aggregation--The default shard size in the terms aggregation now uses BucketUtils.suggestShardSideQueueSize() to set the shard size if the user does not specify it as a parameter.--Closes -6857-,p,https://github.com/elastic/elasticsearch,"diff --git a/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsParser.java b/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsParser.java index c4b57064e80eb..c38f136dd9b29 100644 --- a/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsParser.java +++ b/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsParser.java @@ -21,6 +21,7 @@ import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.search.aggregations.Aggregator; import org.elasticsearch.search.aggregations.AggregatorFactory; +import org.elasticsearch.search.aggregations.bucket.BucketUtils; import org.elasticsearch.search.aggregations.bucket.terms.support.IncludeExclude; import org.elasticsearch.search.aggregations.support.ValuesSourceParser; import org.elasticsearch.search.internal.SearchContext; @@ -32,7 +33,6 @@ */ public class TermsParser implements Aggregator.Parser { - @Override public String type() { return StringTerms.TYPE.name(); @@ -41,19 +41,22 @@ public String type() { @Override public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException { TermsParametersParser aggParser = new TermsParametersParser(); - ValuesSourceParser vsParser = ValuesSourceParser.any(aggregationName, StringTerms.TYPE, context) - .scriptable(true) - .formattable(true) - .requiresSortedValues(true) - .requiresUniqueValues(true) - .build(); + ValuesSourceParser vsParser = ValuesSourceParser.any(aggregationName, StringTerms.TYPE, context).scriptable(true).formattable(true) + .requiresSortedValues(true).requiresUniqueValues(true).build(); IncludeExclude.Parser incExcParser = new IncludeExclude.Parser(aggregationName, StringTerms.TYPE, context); aggParser.parse(aggregationName, parser, context, vsParser, incExcParser); + InternalOrder order = resolveOrder(aggParser.getOrderKey(), aggParser.isOrderAsc()); TermsAggregator.BucketCountThresholds bucketCountThresholds = aggParser.getBucketCountThresholds(); + if (!(order == InternalOrder.TERM_ASC || order == InternalOrder.TERM_DESC) + && bucketCountThresholds.getShardSize() == aggParser.getDefaultBucketCountThresholds().getShardSize()) { + // The user has not made a shardSize selection. Use default heuristic to avoid any wrong-ranking caused by distributed counting + bucketCountThresholds.setShardSize(BucketUtils.suggestShardSideQueueSize(bucketCountThresholds.getRequiredSize(), + context.numberOfShards())); + } bucketCountThresholds.ensureValidity(); - InternalOrder order = resolveOrder(aggParser.getOrderKey(), aggParser.isOrderAsc()); - return new TermsAggregatorFactory(aggregationName, vsParser.config(), order, bucketCountThresholds, aggParser.getIncludeExclude(), aggParser.getExecutionHint(), aggParser.getCollectionMode()); + return new TermsAggregatorFactory(aggregationName, vsParser.config(), order, bucketCountThresholds, aggParser.getIncludeExclude(), + aggParser.getExecutionHint(), aggParser.getCollectionMode()); } static InternalOrder resolveOrder(String key, boolean asc) { diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/ShardSizeTermsTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/ShardSizeTermsTests.java index 7251617f374ee..4bdaecc646d0c 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/bucket/ShardSizeTermsTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/ShardSizeTermsTests.java @@ -45,6 +45,31 @@ public void noShardSize_string() throws Exception { .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.count(false))) .execute().actionGet(); + Terms terms = response.getAggregations().get(""keys""); + Collection buckets = terms.getBuckets(); + assertThat(buckets.size(), equalTo(3)); + Map expected = ImmutableMap.builder() + .put(""1"", 8l) + .put(""3"", 8l) + .put(""2"", 5l) + .build(); + for (Terms.Bucket bucket : buckets) { + assertThat(bucket.getDocCount(), equalTo(expected.get(bucket.getKeyAsText().string()))); + } + } + + @Test + public void shardSizeEqualsSize_string() throws Exception { + createIdx(""type=string,index=not_analyzed""); + + indexData(); + + SearchResponse response = client().prepareSearch(""idx"").setTypes(""type"") + .setQuery(matchAllQuery()) + .addAggregation(terms(""keys"").field(""key"").size(3).shardSize(3) + .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.count(false))) + .execute().actionGet(); + Terms terms = response.getAggregations().get(""keys""); Collection buckets = terms.getBuckets(); assertThat(buckets.size(), equalTo(3)); @@ -109,6 +134,31 @@ public void withShardSize_string_singleShard() throws Exception { assertThat(bucket.getDocCount(), equalTo(expected.get(bucket.getKey()))); } } + + @Test + public void noShardSizeTermOrder_string() throws Exception { + createIdx(""type=string,index=not_analyzed""); + + indexData(); + + SearchResponse response = client().prepareSearch(""idx"").setTypes(""type"") + .setQuery(matchAllQuery()) + .addAggregation(terms(""keys"").field(""key"").size(3) + .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.term(true))) + .execute().actionGet(); + + Terms terms = response.getAggregations().get(""keys""); + Collection buckets = terms.getBuckets(); + assertThat(buckets.size(), equalTo(3)); + Map expected = ImmutableMap.builder() + .put(""1"", 8l) + .put(""2"", 5l) + .put(""3"", 8l) + .build(); + for (Terms.Bucket bucket : buckets) { + assertThat(bucket.getDocCount(), equalTo(expected.get(bucket.getKeyAsText().string()))); + } + } @Test public void noShardSize_long() throws Exception { @@ -123,6 +173,32 @@ public void noShardSize_long() throws Exception { .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.count(false))) .execute().actionGet(); + Terms terms = response.getAggregations().get(""keys""); + Collection buckets = terms.getBuckets(); + assertThat(buckets.size(), equalTo(3)); + Map expected = ImmutableMap.builder() + .put(1, 8l) + .put(3, 8l) + .put(2, 5l) + .build(); + for (Terms.Bucket bucket : buckets) { + assertThat(bucket.getDocCount(), equalTo(expected.get(bucket.getKeyAsNumber().intValue()))); + } + } + + @Test + public void shardSizeEqualsSize_long() throws Exception { + + createIdx(""type=long""); + + indexData(); + + SearchResponse response = client().prepareSearch(""idx"").setTypes(""type"") + .setQuery(matchAllQuery()) + .addAggregation(terms(""keys"").field(""key"").size(3).shardSize(3) + .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.count(false))) + .execute().actionGet(); + Terms terms = response.getAggregations().get(""keys""); Collection buckets = terms.getBuckets(); assertThat(buckets.size(), equalTo(3)); @@ -188,6 +264,32 @@ public void withShardSize_long_singleShard() throws Exception { } } + @Test + public void noShardSizeTermOrder_long() throws Exception { + + createIdx(""type=long""); + + indexData(); + + SearchResponse response = client().prepareSearch(""idx"").setTypes(""type"") + .setQuery(matchAllQuery()) + .addAggregation(terms(""keys"").field(""key"").size(3) + .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.term(true))) + .execute().actionGet(); + + Terms terms = response.getAggregations().get(""keys""); + Collection buckets = terms.getBuckets(); + assertThat(buckets.size(), equalTo(3)); + Map expected = ImmutableMap.builder() + .put(1, 8l) + .put(2, 5l) + .put(3, 8l) + .build(); + for (Terms.Bucket bucket : buckets) { + assertThat(bucket.getDocCount(), equalTo(expected.get(bucket.getKeyAsNumber().intValue()))); + } + } + @Test public void noShardSize_double() throws Exception { @@ -201,6 +303,32 @@ public void noShardSize_double() throws Exception { .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.count(false))) .execute().actionGet(); + Terms terms = response.getAggregations().get(""keys""); + Collection buckets = terms.getBuckets(); + assertThat(buckets.size(), equalTo(3)); + Map expected = ImmutableMap.builder() + .put(1, 8l) + .put(3, 8l) + .put(2, 5l) + .build(); + for (Terms.Bucket bucket : buckets) { + assertThat(bucket.getDocCount(), equalTo(expected.get(bucket.getKeyAsNumber().intValue()))); + } + } + + @Test + public void shardSizeEqualsSize_double() throws Exception { + + createIdx(""type=double""); + + indexData(); + + SearchResponse response = client().prepareSearch(""idx"").setTypes(""type"") + .setQuery(matchAllQuery()) + .addAggregation(terms(""keys"").field(""key"").size(3).shardSize(3) + .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.count(false))) + .execute().actionGet(); + Terms terms = response.getAggregations().get(""keys""); Collection buckets = terms.getBuckets(); assertThat(buckets.size(), equalTo(3)); @@ -265,4 +393,30 @@ public void withShardSize_double_singleShard() throws Exception { assertThat(bucket.getDocCount(), equalTo(expected.get(bucket.getKeyAsNumber().intValue()))); } } + + @Test + public void noShardSizeTermOrder_double() throws Exception { + + createIdx(""type=double""); + + indexData(); + + SearchResponse response = client().prepareSearch(""idx"").setTypes(""type"") + .setQuery(matchAllQuery()) + .addAggregation(terms(""keys"").field(""key"").size(3) + .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.term(true))) + .execute().actionGet(); + + Terms terms = response.getAggregations().get(""keys""); + Collection buckets = terms.getBuckets(); + assertThat(buckets.size(), equalTo(3)); + Map expected = ImmutableMap.builder() + .put(1, 8l) + .put(2, 5l) + .put(3, 8l) + .build(); + for (Terms.Bucket bucket : buckets) { + assertThat(bucket.getDocCount(), equalTo(expected.get(bucket.getKeyAsNumber().intValue()))); + } + } }" 420d11911bbfd59192bfefc061fdc253e326647c,spring-framework,SPR-5973: Extract UriComponentTemplate out of- UriTemplate--,p,https://github.com/spring-projects/spring-framework,"diff --git a/org.springframework.web/src/main/java/org/springframework/web/util/UriBuilder.java b/org.springframework.web/src/main/java/org/springframework/web/util/UriBuilder.java index f2e0b7364d0c..b27db5b16a64 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/util/UriBuilder.java +++ b/org.springframework.web/src/main/java/org/springframework/web/util/UriBuilder.java @@ -220,8 +220,8 @@ private URI buildFromMap(boolean encodeUriVariableValues, Map uriVari UriTemplate template; if (scheme != null) { - template = new UriTemplate(scheme, UriComponent.SCHEME); - uriBuilder.append(template.expandAsString(encodeUriVariableValues, uriVariables)); + template = new UriComponentTemplate(scheme, UriComponent.SCHEME, encodeUriVariableValues); + uriBuilder.append(template.expandAsString(uriVariables)); uriBuilder.append(':'); } @@ -229,14 +229,14 @@ private URI buildFromMap(boolean encodeUriVariableValues, Map uriVari uriBuilder.append(""//""); if (StringUtils.hasLength(userInfo)) { - template = new UriTemplate(userInfo, UriComponent.USER_INFO); - uriBuilder.append(template.expandAsString(encodeUriVariableValues, uriVariables)); + template = new UriComponentTemplate(userInfo, UriComponent.USER_INFO, encodeUriVariableValues); + uriBuilder.append(template.expandAsString(uriVariables)); uriBuilder.append('@'); } if (host != null) { - template = new UriTemplate(host, UriComponent.HOST); - uriBuilder.append(template.expandAsString(encodeUriVariableValues, uriVariables)); + template = new UriComponentTemplate(host, UriComponent.HOST, encodeUriVariableValues); + uriBuilder.append(template.expandAsString(uriVariables)); } if (port != -1) { @@ -256,20 +256,20 @@ private URI buildFromMap(boolean encodeUriVariableValues, Map uriVari else if (endsWithSlash && startsWithSlash) { pathSegment = pathSegment.substring(1); } - template = new UriTemplate(pathSegment, UriComponent.PATH_SEGMENT); - uriBuilder.append(template.expandAsString(encodeUriVariableValues, uriVariables)); + template = new UriComponentTemplate(pathSegment, UriComponent.PATH_SEGMENT, encodeUriVariableValues); + uriBuilder.append(template.expandAsString(uriVariables)); } } if (queryBuilder.length() > 0) { uriBuilder.append('?'); - template = new UriTemplate(queryBuilder.toString(), UriComponent.QUERY); - uriBuilder.append(template.expandAsString(encodeUriVariableValues, uriVariables)); + template = new UriComponentTemplate(queryBuilder.toString(), UriComponent.QUERY, encodeUriVariableValues); + uriBuilder.append(template.expandAsString(uriVariables)); } if (StringUtils.hasLength(fragment)) { uriBuilder.append('#'); - template = new UriTemplate(fragment, UriComponent.FRAGMENT); - uriBuilder.append(template.expandAsString(encodeUriVariableValues, uriVariables)); + template = new UriComponentTemplate(fragment, UriComponent.FRAGMENT, encodeUriVariableValues); + uriBuilder.append(template.expandAsString(uriVariables)); } return URI.create(uriBuilder.toString()); @@ -308,8 +308,8 @@ private URI buildFromVarArg(boolean encodeUriVariableValues, Object... uriVariab UriTemplate template; if (scheme != null) { - template = new UriTemplate(scheme, UriComponent.SCHEME); - uriBuilder.append(template.expandAsString(encodeUriVariableValues, uriVariableValues)); + template = new UriComponentTemplate(scheme, UriComponent.SCHEME, encodeUriVariableValues); + uriBuilder.append(template.expandAsString(uriVariableValues)); uriBuilder.append(':'); } @@ -317,14 +317,14 @@ private URI buildFromVarArg(boolean encodeUriVariableValues, Object... uriVariab uriBuilder.append(""//""); if (StringUtils.hasLength(userInfo)) { - template = new UriTemplate(userInfo, UriComponent.USER_INFO); - uriBuilder.append(template.expandAsString(encodeUriVariableValues, uriVariableValues)); + template = new UriComponentTemplate(userInfo, UriComponent.USER_INFO, encodeUriVariableValues); + uriBuilder.append(template.expandAsString(uriVariableValues)); uriBuilder.append('@'); } if (host != null) { - template = new UriTemplate(host, UriComponent.HOST); - uriBuilder.append(template.expandAsString(encodeUriVariableValues, uriVariableValues)); + template = new UriComponentTemplate(host, UriComponent.HOST, encodeUriVariableValues); + uriBuilder.append(template.expandAsString(uriVariableValues)); } if (port != -1) { @@ -344,21 +344,21 @@ private URI buildFromVarArg(boolean encodeUriVariableValues, Object... uriVariab else if (endsWithSlash && startsWithSlash) { pathSegment = pathSegment.substring(1); } - template = new UriTemplate(pathSegment, UriComponent.PATH_SEGMENT); - uriBuilder.append(template.expandAsString(encodeUriVariableValues, uriVariableValues)); + template = new UriComponentTemplate(pathSegment, UriComponent.PATH_SEGMENT, encodeUriVariableValues); + uriBuilder.append(template.expandAsString(uriVariableValues)); } } if (queryBuilder.length() > 0) { uriBuilder.append('?'); - template = new UriTemplate(queryBuilder.toString(), UriComponent.QUERY); - uriBuilder.append(template.expandAsString(encodeUriVariableValues, uriVariableValues)); + template = new UriComponentTemplate(queryBuilder.toString(), UriComponent.QUERY, encodeUriVariableValues); + uriBuilder.append(template.expandAsString(uriVariableValues)); } if (StringUtils.hasLength(fragment)) { uriBuilder.append('#'); - template = new UriTemplate(fragment, UriComponent.FRAGMENT); - uriBuilder.append(template.expandAsString(encodeUriVariableValues, uriVariableValues)); + template = new UriComponentTemplate(fragment, UriComponent.FRAGMENT, encodeUriVariableValues); + uriBuilder.append(template.expandAsString(uriVariableValues)); } return URI.create(uriBuilder.toString()); diff --git a/org.springframework.web/src/main/java/org/springframework/web/util/UriComponentTemplate.java b/org.springframework.web/src/main/java/org/springframework/web/util/UriComponentTemplate.java new file mode 100644 index 000000000000..d354ca2dcc3f --- /dev/null +++ b/org.springframework.web/src/main/java/org/springframework/web/util/UriComponentTemplate.java @@ -0,0 +1,46 @@ +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.web.util; + +import org.springframework.util.Assert; + +/** + * Subclass of {@link UriTemplate} that operates on URI components, rather than full URIs. + * + * @author Arjen Poutsma + * @since 3.1 + */ +class UriComponentTemplate extends UriTemplate { + + private final UriComponent uriComponent; + + private boolean encodeUriVariableValues; + + UriComponentTemplate(String uriTemplate, UriComponent uriComponent, boolean encodeUriVariableValues) { + super(uriTemplate); + Assert.notNull(uriComponent, ""'uriComponent' must not be null""); + this.uriComponent = uriComponent; + this.encodeUriVariableValues = encodeUriVariableValues; + } + + @Override + protected String getVariableValueAsString(Object variableValue) { + String variableValueString = super.getVariableValueAsString(variableValue); + return encodeUriVariableValues ? UriUtils.encode(variableValueString, uriComponent, false) : + variableValueString; + } +} diff --git a/org.springframework.web/src/main/java/org/springframework/web/util/UriTemplate.java b/org.springframework.web/src/main/java/org/springframework/web/util/UriTemplate.java index 51ebb224600e..6026020b9761 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/util/UriTemplate.java +++ b/org.springframework.web/src/main/java/org/springframework/web/util/UriTemplate.java @@ -56,8 +56,6 @@ public class UriTemplate implements Serializable { private final String uriTemplate; - private final UriComponent uriComponent; - /** * Construct a new {@link UriTemplate} with the given URI String. @@ -68,19 +66,6 @@ public UriTemplate(String uriTemplate) { this.uriTemplate = uriTemplate; this.variableNames = parser.getVariableNames(); this.matchPattern = parser.getMatchPattern(); - this.uriComponent = null; - } - - /** - * Construct a new {@link UriTemplate} with the given URI String. - * @param uriTemplate the URI template string - */ - public UriTemplate(String uriTemplate, UriComponent uriComponent) { - Parser parser = new Parser(uriTemplate); - this.uriTemplate = uriTemplate; - this.variableNames = parser.getVariableNames(); - this.matchPattern = parser.getMatchPattern(); - this.uriComponent = uriComponent; } /** @@ -110,7 +95,7 @@ public List getVariableNames() { * or if it does not contain values for all the variable names */ public URI expand(Map uriVariables) { - return encodeUri(expandAsString(false, uriVariables)); + return encodeUri(expandAsString(uriVariables)); } /** @@ -125,13 +110,13 @@ public URI expand(Map uriVariables) { * System.out.println(template.expand(uriVariables)); * * will print:
http://example.com/hotels/1/bookings/42
- * @param encodeUriVariableValues indicates whether uri template variables should be encoded or not + * * @param uriVariables the map of URI variables * @return the expanded URI * @throws IllegalArgumentException if uriVariables is null; * or if it does not contain values for all the variable names */ - public String expandAsString(boolean encodeUriVariableValues, Map uriVariables) { + public String expandAsString(Map uriVariables) { Assert.notNull(uriVariables, ""'uriVariables' must not be null""); Object[] values = new Object[this.variableNames.size()]; for (int i = 0; i < this.variableNames.size(); i++) { @@ -141,7 +126,7 @@ public String expandAsString(boolean encodeUriVariableValues, Map uri } values[i] = uriVariables.get(name); } - return expandAsString(encodeUriVariableValues, values); + return expandAsString(values); } /** @@ -159,7 +144,7 @@ public String expandAsString(boolean encodeUriVariableValues, Map uri * or if it does not contain sufficient variables */ public URI expand(Object... uriVariableValues) { - return encodeUri(expandAsString(false, uriVariableValues)); + return encodeUri(expandAsString(uriVariableValues)); } /** @@ -171,13 +156,13 @@ public URI expand(Object... uriVariableValues) { * System.out.println(template.expand(""1"", ""42)); * * will print:
http://example.com/hotels/1/bookings/42
- * @param encodeVariableValues indicates whether uri template variables should be encoded or not + * * @param uriVariableValues the array of URI variables * @return the expanded URI * @throws IllegalArgumentException if uriVariables is null * or if it does not contain sufficient variables */ - public String expandAsString(boolean encodeVariableValues, Object... uriVariableValues) { + public String expandAsString(Object... uriVariableValues) { Assert.notNull(uriVariableValues, ""'uriVariableValues' must not be null""); if (uriVariableValues.length < this.variableNames.size()) { throw new IllegalArgumentException( @@ -188,18 +173,27 @@ public String expandAsString(boolean encodeVariableValues, Object... uriVariable StringBuffer uriBuffer = new StringBuffer(); int i = 0; while (matcher.find()) { - Object uriVariable = uriVariableValues[i++]; - String uriVariableString = uriVariable != null ? uriVariable.toString() : """"; - if (encodeVariableValues && uriComponent != null) { - uriVariableString = UriUtils.encode(uriVariableString, uriComponent, false); - } - String replacement = Matcher.quoteReplacement(uriVariableString); + Object uriVariableValue = uriVariableValues[i++]; + String uriVariableValueString = getVariableValueAsString(uriVariableValue); + String replacement = Matcher.quoteReplacement(uriVariableValueString); matcher.appendReplacement(uriBuffer, replacement); } matcher.appendTail(uriBuffer); return uriBuffer.toString(); } + /** + * Template method that returns the string representation of the given URI template value. + * + *

Defaults implementation simply calls {@link Object#toString()}, or returns an empty string for {@code null}. + * + * @param variableValue the URI template variable value + * @return the variable value as string + */ + protected String getVariableValueAsString(Object variableValue) { + return variableValue != null ? variableValue.toString() : """"; + } + /** * Indicate whether the given URI matches this template. * @param uri the URI to match to" f3554235b3abb5b5820b57f932398af5a8846b32,Delta Spike,"adding release notes draft for upcoming deltaspike-0.5 release ",p,https://github.com/apache/deltaspike,"diff --git a/deltaspike/readme/ReleaseNotes-0.5.txt b/deltaspike/readme/ReleaseNotes-0.5.txt new file mode 100644 index 000000000..ea682196b --- /dev/null +++ b/deltaspike/readme/ReleaseNotes-0.5.txt @@ -0,0 +1,30 @@ +Apache DeltaSpike-0.5 Release Notes + + +The following modules and big features got added in the DeltaSpike-0.5 release: + +* DeltaSpike-Data + +The DeltaSpike Data module enhances JPA experience with declarative +queries, reducing boilerplate to a minimum. DeltaSpike Data repositories +can derive queries by simple method names, or by method annotations +defining JPQL, named queries or even plain SQL - beside result pagination +and sorting. The module also features auditing of entities and a simplified +alternative to the Criteria API. + + +* DeltaSpike-Servlet + +The DeltaSpike Servlet module provides integration with the Java Servlet +API. It adds support for injection of common servlet objects +and propagates servlet events to the CDI event bus. + + +* DeltaSpike-BeanValidation + +The main feature of the Bean Validation module is to provide +CDI integration in to ConstraintValidators. This allows you to +inject CDI objects, EJBs etc in to your validators. + + +" cd2f14637bcecec0081104d749cd1bf10f28b07d,ReactiveX-RxJava,Fixed issue -799 - Added break to possibly-infinite- loop in CompositeException.attachCallingThreadStack--,c,https://github.com/ReactiveX/RxJava,"diff --git a/rxjava-core/src/main/java/rx/util/CompositeException.java b/rxjava-core/src/main/java/rx/util/CompositeException.java index bca5dcfbf7..439b9400b2 100644 --- a/rxjava-core/src/main/java/rx/util/CompositeException.java +++ b/rxjava-core/src/main/java/rx/util/CompositeException.java @@ -18,7 +18,9 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.HashSet; import java.util.List; +import java.util.Set; /** * Exception that is a composite of 1 or more other exceptions. @@ -84,9 +86,16 @@ private static String getStackTraceAsString(StackTraceElement[] stack) { return s.toString(); } - private static void attachCallingThreadStack(Throwable e, Throwable cause) { + /* package-private */ static void attachCallingThreadStack(Throwable e, Throwable cause) { + Set seenCauses = new HashSet(); + while (e.getCause() != null) { e = e.getCause(); + if (seenCauses.contains(e.getCause())) { + break; + } else { + seenCauses.add(e.getCause()); + } } // we now have 'e' as the last in the chain try { @@ -98,12 +107,13 @@ private static void attachCallingThreadStack(Throwable e, Throwable cause) { } } - private final static class CompositeExceptionCausalChain extends RuntimeException { + /* package-private */ final static class CompositeExceptionCausalChain extends RuntimeException { private static final long serialVersionUID = 3875212506787802066L; + /* package-private */ static String MESSAGE = ""Chain of Causes for CompositeException In Order Received =>""; @Override public String getMessage() { - return ""Chain of Causes for CompositeException In Order Received =>""; + return MESSAGE; } } diff --git a/rxjava-core/src/test/java/rx/util/CompositeExceptionTest.java b/rxjava-core/src/test/java/rx/util/CompositeExceptionTest.java new file mode 100644 index 0000000000..0e80cf0309 --- /dev/null +++ b/rxjava-core/src/test/java/rx/util/CompositeExceptionTest.java @@ -0,0 +1,70 @@ +/** + * Copyright 2013 Netflix, Inc. + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package rx.util; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +public class CompositeExceptionTest { + + private final Throwable ex1 = new Throwable(""Ex1""); + private final Throwable ex2 = new Throwable(""Ex2"", ex1); + private final Throwable ex3 = new Throwable(""Ex3"", ex2); + + private final CompositeException compositeEx; + + public CompositeExceptionTest() { + List throwables = new ArrayList(); + throwables.add(ex1); + throwables.add(ex2); + throwables.add(ex3); + compositeEx = new CompositeException(throwables); + } + + @Test + public void testAttachCallingThreadStackParentThenChild() { + CompositeException.attachCallingThreadStack(ex1, ex2); + assertEquals(""Ex2"", ex1.getCause().getMessage()); + } + + @Test + public void testAttachCallingThreadStackChildThenParent() { + CompositeException.attachCallingThreadStack(ex2, ex1); + assertEquals(""Ex1"", ex2.getCause().getMessage()); + } + + @Test + public void testAttachCallingThreadStackAddComposite() { + CompositeException.attachCallingThreadStack(ex1, compositeEx); + assertEquals(""Ex2"", ex1.getCause().getMessage()); + } + + @Test + public void testAttachCallingThreadStackAddToComposite() { + CompositeException.attachCallingThreadStack(compositeEx, ex1); + assertEquals(CompositeException.CompositeExceptionCausalChain.MESSAGE, compositeEx.getCause().getMessage()); + } + + @Test + public void testAttachCallingThreadStackAddCompositeToItself() { + CompositeException.attachCallingThreadStack(compositeEx, compositeEx); + assertEquals(CompositeException.CompositeExceptionCausalChain.MESSAGE, compositeEx.getCause().getMessage()); + } +} \ No newline at end of file" 4043b1d38140d531f5f97d4f87850f168283c240,spring-framework,Workaround Javadoc bug with JDK 8 (b112+)--Remove Javadoc linkplain to ExceptionHandler-value() from-AnnotationMethodHandlerExceptionResolver to work around JDK-Javadoc bug 9007707.-,c,https://github.com/spring-projects/spring-framework,"diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerExceptionResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerExceptionResolver.java index 1450d8a9683a..65bba17c3830 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerExceptionResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerExceptionResolver.java @@ -206,7 +206,7 @@ public void doWith(Method method) { /** * Returns all the exception classes handled by the given method. - *

The default implementation looks for exceptions in the {@linkplain ExceptionHandler#value() annotation}, + *

The default implementation looks for exceptions in the annotation, * or - if that annotation element is empty - any exceptions listed in the method parameters if the method * is annotated with {@code @ExceptionHandler}. * @param method the method" 95ba62f83dfa05990d2165484330cdd0792064d8,elasticsearch,Translog: Implement a file system based translog- and make it the default,a,https://github.com/elastic/elasticsearch,"diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/translog/TranslogModule.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/translog/TranslogModule.java index 61977707465c0..02c378097c250 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/translog/TranslogModule.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/translog/TranslogModule.java @@ -22,7 +22,7 @@ import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.Scopes; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.index.translog.memory.MemoryTranslog; +import org.elasticsearch.index.translog.fs.FsTranslog; /** * @author kimchy (shay.banon) @@ -41,7 +41,7 @@ public TranslogModule(Settings settings) { @Override protected void configure() { bind(Translog.class) - .to(settings.getAsClass(TranslogSettings.TYPE, MemoryTranslog.class)) + .to(settings.getAsClass(TranslogSettings.TYPE, FsTranslog.class)) .in(Scopes.SINGLETON); } }" bb85cacf9358f9ed289e72a416e78625fcab18a4,Delta Spike,"DELTASPIKE-289 fix WindowScoped context test on jbossas I recently removed the which did lead to a different component Id for the outputValue. fixed now. ",p,https://github.com/apache/deltaspike,"diff --git a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/WindowScopedContextTest.java b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/WindowScopedContextTest.java index c57b16c48..a6e97cb28 100644 --- a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/WindowScopedContextTest.java +++ b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/WindowScopedContextTest.java @@ -20,6 +20,7 @@ import java.net.URL; +import java.util.logging.Logger; import org.apache.deltaspike.test.category.WebProfileCategory; import org.apache.deltaspike.test.jsf.impl.scope.window.beans.WindowScopedBackingBean; @@ -51,6 +52,8 @@ @Category(WebProfileCategory.class) public class WindowScopedContextTest { + private static final Logger log = Logger.getLogger(WindowScopedContextTest.class.getName()); + @Drone private WebDriver driver; @@ -79,14 +82,12 @@ public static WebArchive deploy() public void testWindowId() throws Exception { System.out.println(""contextpath= "" + contextPath); - //X - Thread.sleep(600000L); - - driver.get(new URL(contextPath, ""page.xhtml"").toString()); //X comment this in if you like to debug the server //X I've already reported ARQGRA-213 for it - //X + //X Thread.sleep(600000L); + + driver.get(new URL(contextPath, ""page.xhtml"").toString()); WebElement inputField = driver.findElement(By.id(""test:valueInput"")); inputField.sendKeys(""23""); @@ -94,7 +95,7 @@ public void testWindowId() throws Exception WebElement button = driver.findElement(By.id(""test:saveButton"")); button.click(); - Assert.assertTrue(ExpectedConditions.textToBePresentInElement(By.id(""test:valueOutput""), ""23"").apply(driver)); + Assert.assertTrue(ExpectedConditions.textToBePresentInElement(By.id(""valueOutput""), ""23"").apply(driver)); }" a09d266b247b185054d0ab0dfdb6e8dc2e8898bc,orientdb,Minor: removed some warnings--,p,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexManager.java b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexManager.java index f5fe061175a..dcf7d2ae48b 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexManager.java +++ b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexManager.java @@ -32,13 +32,13 @@ public interface OIndexManager { public void create(); - public Collection getIndexes(); + public Collection> getIndexes(); - public OIndex getIndex(final String iName); + public OIndex getIndex(final String iName); - public OIndex getIndex(final ORID iRID); + public OIndex getIndex(final ORID iRID); - public OIndex createIndex(final String iName, final String iType, final OType iKeyType, final int[] iClusterIdsToIndex, + public OIndex createIndex(final String iName, final String iType, final OType iKeyType, final int[] iClusterIdsToIndex, OIndexCallback iCallback, final OProgressListener iProgressListener, final boolean iAutomatic); public OIndexManager dropIndex(final String iIndexName); diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexManagerProxy.java b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexManagerProxy.java index d0a9eadd979..7b403ff8d30 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexManagerProxy.java +++ b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexManagerProxy.java @@ -47,24 +47,24 @@ public void create() { delegate.create(); } - public Collection getIndexes() { + public Collection> getIndexes() { return delegate.getIndexes(); } - public OIndex getIndex(String iName) { + public OIndex getIndex(String iName) { return delegate.getIndex(iName); } - public OIndex getIndex(ORID iRID) { + public OIndex getIndex(ORID iRID) { return delegate.getIndex(iRID); } - public OIndex createIndex(String iName, String iType, final OType iKeyType, int[] iClusterIdsToIndex, OIndexCallback iCallback, + public OIndex createIndex(String iName, String iType, final OType iKeyType, int[] iClusterIdsToIndex, OIndexCallback iCallback, OProgressListener iProgressListener, boolean iAutomatic) { return delegate.createIndex(iName, iType, iKeyType, iClusterIdsToIndex, iCallback, iProgressListener, iAutomatic); } - public OIndex getIndexInternal(final String iName) { + public OIndex getIndexInternal(final String iName) { return ((OIndexManagerShared) delegate).getIndexInternal(iName); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java index d85b127e2d9..10e8f89b848 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java @@ -108,9 +108,9 @@ public class OCommandExecutorSQLSelect extends OCommandExecutorSQLAbstract imple private static final class OSearchInIndexTriple { private OQueryOperator indexOperator; private Object key; - private OIndex index; + private OIndex index; - private OSearchInIndexTriple(final OQueryOperator indexOperator, final Object key, final OIndex index) { + private OSearchInIndexTriple(final OQueryOperator indexOperator, final Object key, final OIndex index) { this.indexOperator = indexOperator; this.key = key; this.index = index; @@ -120,7 +120,6 @@ private OSearchInIndexTriple(final OQueryOperator indexOperator, final Object ke /** * Compile the filter conditions only the first time. */ - @SuppressWarnings(""unchecked"") public OCommandExecutorSQLSelect parse(final OCommandRequestText iRequest) { iRequest.getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); @@ -386,7 +385,7 @@ private boolean searchForIndexes(final List> iResultSet, final OClass return false; for (OSearchInIndexTriple indexTriple : searchInIndexTriples) { - final OIndex idx = indexTriple.index.getInternal(); + final OIndex idx = indexTriple.index.getInternal(); final OQueryOperator operator = indexTriple.indexOperator; final Object key = indexTriple.key; @@ -482,7 +481,7 @@ private boolean searchIndexedProperty(OClass iSchemaClass, final OSQLFilterCondi if (prop != null && prop.isIndexed()) { final Object origValue = iCondition.getLeft() == iItem ? iCondition.getRight() : iCondition.getLeft(); - final OIndex underlyingIndex = prop.getIndex().getUnderlying(); + final OIndex underlyingIndex = prop.getIndex().getUnderlying(); if (iCondition.getOperator() instanceof OQueryOperatorBetween) { iSearchInIndexTriples.add(new OSearchInIndexTriple(iCondition.getOperator(), origValue, underlyingIndex)); @@ -788,7 +787,8 @@ record = database.load(rid); } private void searchInIndex() { - final OIndex index = database.getMetadata().getIndexManager().getIndex(compiledFilter.getTargetIndex()); + final OIndex index = (OIndex) database.getMetadata().getIndexManager() + .getIndex(compiledFilter.getTargetIndex()); if (index == null) throw new OCommandExecutionException(""Target index '"" + compiledFilter.getTargetIndex() + ""' not found""); diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/IndexTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/IndexTest.java index 280c175c157..dac497b5198 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/IndexTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/IndexTest.java @@ -706,7 +706,7 @@ public void createNotUniqueIndexOnNick() { public void LongTypes() { database.getMetadata().getSchema().getClass(""Profile"").createProperty(""hash"", OType.LONG).createIndex(INDEX_TYPE.UNIQUE); - OIndex idx = database.getMetadata().getIndexManager().getIndex(""Profile.hash""); + OIndex idx = (OIndex) database.getMetadata().getIndexManager().getIndex(""Profile.hash""); for (int i = 0; i < 5; i++) { Profile profile = new Profile(""HashTest1"").setHash(100l + i);" a9a93876f2ead9468fd50eba715083c9a7e8a52a,drools,JBRULES-3714 Add capability to configure- date-effective/date-expires for SpreadSheet--,a,https://github.com/kiegroup/drools,"diff --git a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java index 73cb78135c8..9fe46429cd8 100644 --- a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java +++ b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java @@ -46,6 +46,8 @@ public enum Code { ACTIVATIONGROUP( ""ACTIVATION-GROUP"", ""X"", 1 ), AGENDAGROUP( ""AGENDA-GROUP"", ""G"", 1 ), RULEFLOWGROUP( ""RULEFLOW-GROUP"", ""R"", 1 ), + DATEEFFECTIVE( ""DATE-EFFECTIVE"", ""V"", 1 ), + DATEEXPIRES( ""DATE-EXPIRES"", ""Z"", 1 ), METADATA( ""METADATA"", ""@"" ); private String colHeader; @@ -80,7 +82,7 @@ public int getMaxCount() { } } - public static final EnumSet ATTRIBUTE_CODE_SET = EnumSet.range( Code.SALIENCE, Code.RULEFLOWGROUP ); + public static final EnumSet ATTRIBUTE_CODE_SET = EnumSet.range( Code.SALIENCE, Code.DATEEXPIRES ); private static final Map tag2code = new HashMap(); static { diff --git a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java index 1e513078472..c5ba2bb178d 100644 --- a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java +++ b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java @@ -240,6 +240,12 @@ private Package buildRuleSet() { case RULEFLOWGROUP: ruleset.setRuleFlowGroup( value ); break; + case DATEEFFECTIVE: + ruleset.setDateEffective( value ); + break; + case DATEEXPIRES: + ruleset.setDateExpires( value ); + break; } } } @@ -648,6 +654,12 @@ private void nextDataCell(final int row, case CALENDARS: this._currentRule.setCalendars( value ); break; + case DATEEFFECTIVE: + this._currentRule.setDateEffective( value ); + break; + case DATEEXPIRES: + this._currentRule.setDateExpires( value ); + break; } } diff --git a/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java b/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java index 1b6e45ff102..150eac13869 100644 --- a/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java +++ b/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java @@ -192,6 +192,10 @@ public void testAttributesXLS() { rule1 ) > -1 ); assertTrue( drl.indexOf( ""calendars \""CAL1\"""", rule1 ) > -1 ); + assertTrue( drl.indexOf( ""date-effective \""01-Jan-2007\"""", + rule1 ) > -1 ); + assertTrue( drl.indexOf( ""date-expires \""31-Dec-2007\"""", + rule1 ) > -1 ); int rule2 = drl.indexOf( ""rule \""N2\"""" ); assertFalse( rule2 == -1 ); @@ -216,6 +220,10 @@ public void testAttributesXLS() { rule2 ) > -1 ); assertTrue( drl.indexOf( ""calendars \""CAL2\"""", rule2 ) > -1 ); + assertTrue( drl.indexOf( ""date-effective \""01-Jan-2012\"""", + rule2 ) > -1 ); + assertTrue( drl.indexOf( ""date-expires \""31-Dec-2015\"""", + rule2 ) > -1 ); } @Test diff --git a/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java b/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java index cbfc6e9644a..6d7bf450be7 100644 --- a/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java +++ b/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java @@ -156,6 +156,26 @@ public void testChooseActionType() { type = (ActionType) actionTypeMap.get( new Integer(0) ); assertEquals(Code.RULEFLOWGROUP, type.getCode()); + actionTypeMap = new HashMap(); + ActionType.addNewActionType( actionTypeMap, ""V"", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.DATEEFFECTIVE, type.getCode()); + + actionTypeMap = new HashMap(); + ActionType.addNewActionType( actionTypeMap, ""DATE-EFFECTIVE"", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.DATEEFFECTIVE, type.getCode()); + + actionTypeMap = new HashMap(); + ActionType.addNewActionType( actionTypeMap, ""Z"", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.DATEEXPIRES, type.getCode()); + + actionTypeMap = new HashMap(); + ActionType.addNewActionType( actionTypeMap, ""DATE-EXPIRES"", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.DATEEXPIRES, type.getCode()); + actionTypeMap = new HashMap(); ActionType.addNewActionType( actionTypeMap, ""@"", 0, 1 ); type = (ActionType) actionTypeMap.get( new Integer(0) ); diff --git a/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls b/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls index 3159e4ffeb6..1819888649a 100644 Binary files a/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls and b/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls differ diff --git a/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java b/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java index b46e25c7c45..3232fb349be 100644 --- a/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java +++ b/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java @@ -105,6 +105,14 @@ public void setAutoFocus(final boolean value) { this._attr2value.put( ""auto-focus"", Boolean.toString( value ) ); } + public void setDateEffective(final String value) { + this._attr2value.put( ""date-effective"", asStringLiteral( value ) ); + } + + public void setDateExpires(final String value) { + this._attr2value.put( ""date-expires"", asStringLiteral( value ) ); + } + public String getAttribute( String name ){ return this._attr2value.get( name ).toString(); }" ce2995c49d111b5749a88b4de2065a3a68551386,hbase,HBASE-1136 HashFunction inadvertently destroys- some randomness; REVERTING--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@735880 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hbase,"diff --git a/CHANGES.txt b/CHANGES.txt index 7e9c80101764..970250b4eaeb 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -3,8 +3,6 @@ Release 0.20.0 - Unreleased INCOMPATIBLE CHANGES BUG FIXES - HBASE-1136 HashFunction inadvertently destroys some randomness - (Jonathan Ellis via Stack) HBASE-1140 ""ant clean test"" fails (Nitay Joffe via Stack) IMPROVEMENTS diff --git a/src/java/org/onelab/filter/HashFunction.java b/src/java/org/onelab/filter/HashFunction.java index cf97c7bcaa26..a0c26964e2f6 100644 --- a/src/java/org/onelab/filter/HashFunction.java +++ b/src/java/org/onelab/filter/HashFunction.java @@ -118,8 +118,7 @@ public int[] hash(Key k){ } int[] result = new int[nbHash]; for (int i = 0, initval = 0; i < nbHash; i++) { - initval = hashFunction.hash(b, initval); - result[i] = Math.abs(initval) % maxValue; + initval = result[i] = Math.abs(hashFunction.hash(b, initval) % maxValue); } return result; }//end hash() diff --git a/src/test/org/onelab/test/TestFilter.java b/src/test/org/onelab/test/TestFilter.java index 363fc9451481..6c88c1ab33f4 100644 --- a/src/test/org/onelab/test/TestFilter.java +++ b/src/test/org/onelab/test/TestFilter.java @@ -274,7 +274,7 @@ public void testCountingBloomFilter() throws UnsupportedEncodingException { bf.add(k2); bf.add(k3); assertTrue(bf.membershipTest(key)); - assertFalse(bf.membershipTest(k2)); + assertTrue(bf.membershipTest(new StringKey(""graknyl""))); assertFalse(bf.membershipTest(new StringKey(""xyzzy""))); assertFalse(bf.membershipTest(new StringKey(""abcd""))); @@ -287,7 +287,7 @@ public void testCountingBloomFilter() throws UnsupportedEncodingException { bf2.add(key); bf.or(bf2); assertTrue(bf.membershipTest(key)); - assertTrue(bf.membershipTest(k2)); + assertTrue(bf.membershipTest(new StringKey(""graknyl""))); assertFalse(bf.membershipTest(new StringKey(""xyzzy""))); assertFalse(bf.membershipTest(new StringKey(""abcd"")));" eb0a1bebaa1486ab4d2af4dccf40aea7f8f1d5dd,Mylyn Reviews,"Merge branch 'master' of git://git.eclipse.org/gitroot/mylyn/org.eclipse.mylyn.reviews ",p,https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews,"diff --git a/framework/org.eclipse.mylyn.reviews.core/build.properties b/framework/org.eclipse.mylyn.reviews.core/build.properties index 9adcaaf4..21815455 100644 --- a/framework/org.eclipse.mylyn.reviews.core/build.properties +++ b/framework/org.eclipse.mylyn.reviews.core/build.properties @@ -10,7 +10,9 @@ bin.includes = .,\ model/,\ plugin.xml,\ - META-INF/ + META-INF/,\ + about.html jars.compile.order = . source.. = src/ output.. = target/classes/ +src.includes = about.html diff --git a/framework/org.eclipse.mylyn.reviews.feature/.settings/org.eclipse.jdt.core.prefs b/framework/org.eclipse.mylyn.reviews.feature/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index bc1e8f9c..00000000 --- a/framework/org.eclipse.mylyn.reviews.feature/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,357 +0,0 @@ -#Wed Mar 02 16:00:03 PST 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.codeComplete.argumentPrefixes= -org.eclipse.jdt.core.codeComplete.argumentSuffixes= -org.eclipse.jdt.core.codeComplete.fieldPrefixes= -org.eclipse.jdt.core.codeComplete.fieldSuffixes= -org.eclipse.jdt.core.codeComplete.localPrefixes= -org.eclipse.jdt.core.codeComplete.localSuffixes= -org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= -org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.5 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=error -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning -org.eclipse.jdt.core.compiler.problem.nullReference=error -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedImport=warning -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.5 -org.eclipse.jdt.core.compiler.taskCaseSensitive=enabled -org.eclipse.jdt.core.compiler.taskPriorities=NORMAL,HIGH,NORMAL -org.eclipse.jdt.core.compiler.taskTags=TODO,FIXME,XXX -org.eclipse.jdt.core.formatter.align_type_members_on_columns=false -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_assignment=0 -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 -org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=48 -org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 -org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 -org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 -org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=80 -org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 -org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_after_package=1 -org.eclipse.jdt.core.formatter.blank_lines_before_field=1 -org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 -org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 -org.eclipse.jdt.core.formatter.blank_lines_before_method=1 -org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 -org.eclipse.jdt.core.formatter.blank_lines_before_package=0 -org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 -org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 -org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.comment.clear_blank_lines=false -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=true -org.eclipse.jdt.core.formatter.comment.format_block_comments=false -org.eclipse.jdt.core.formatter.comment.format_comments=true -org.eclipse.jdt.core.formatter.comment.format_header=false -org.eclipse.jdt.core.formatter.comment.format_html=true -org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true -org.eclipse.jdt.core.formatter.comment.format_line_comments=false -org.eclipse.jdt.core.formatter.comment.format_source_code=true -org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true -org.eclipse.jdt.core.formatter.comment.indent_root_tags=true -org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert -org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert -org.eclipse.jdt.core.formatter.comment.line_length=120 -org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true -org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true -org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false -org.eclipse.jdt.core.formatter.compact_else_if=true -org.eclipse.jdt.core.formatter.continuation_indentation=2 -org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 -org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off -org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on -org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false -org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true -org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_empty_lines=false -org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true -org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false -org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert -org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.join_lines_in_comments=true -org.eclipse.jdt.core.formatter.join_wrapped_lines=true -org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false -org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false -org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false -org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false -org.eclipse.jdt.core.formatter.lineSplit=120 -org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=true -org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=true -org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 -org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 -org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true -org.eclipse.jdt.core.formatter.tabulation.char=tab -org.eclipse.jdt.core.formatter.tabulation.size=4 -org.eclipse.jdt.core.formatter.use_on_off_tags=false -org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false -org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true -org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true diff --git a/framework/org.eclipse.mylyn.reviews.feature/.settings/org.eclipse.jdt.ui.prefs b/framework/org.eclipse.mylyn.reviews.feature/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index e2834b27..00000000 --- a/framework/org.eclipse.mylyn.reviews.feature/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,63 +0,0 @@ -#Wed Mar 02 16:00:04 PST 2011 -cleanup_settings_version=2 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -formatter_profile=_Mylyn based on Eclipse -formatter_settings_version=12 -internal.default.compliance=default -org.eclipse.jdt.ui.exception.name=e -org.eclipse.jdt.ui.gettersetter.use.is=true -org.eclipse.jdt.ui.javadoc=false -org.eclipse.jdt.ui.keywordthis=false -org.eclipse.jdt.ui.overrideannotation=true -org.eclipse.jdt.ui.text.custom_code_templates=